douyi6922 2016-11-11 07:09
浏览 19
已采纳

php datetime输出问题

I fetch datetime in the DB from different columns based on some conditions.

The script in PHP:

if($obj->acct_status == 2)
    $dt = date('d M, Y h:i:s A', strtotime($obj->approve_datetime));

if($obj->acct_status == 4)
    $dt = date('d M, Y h:i:s A', strtotime($obj->suspend_datetime)); 

The DB stores datetime in this format:

2016-11-11 14:26:03

The output:

30 Nov, -0001 12:00:00 AM

What is the cause of this issue?

  • 写回答

1条回答 默认 最新

  • doujiyun0041 2016-11-11 07:23
    关注

    I strongly believe strtotime() should be avoided when there is a format available.

    $from_format = 'Y-m-d H:i:s';
    $to_format   = 'd M, Y h:i:s A';
    $date = '2016-11-11 14:26:03';        
    
    
    echo DateTime::createFromFormat($from_format, $date)->format($to_format);
    

    Outputs:

    11 Nov, 2016 02:26:03 PM
    

    Why your code fails I cannot say for certain, it works fine here but you can diagnose a little. I'm assuming in your case its because strtotime() fails converting, returning -62169984000 which is actually 0000-00-00 00:00:00 but due to a second, minute, day and a month that is not allowed to be 0, calculations occur resulting in 0000-00-00 00:00:00 minus 1 day and 1 month, etc being 30 Nov -0001 12:00:00 so it would appear your $obj->suspend_datetime does not contain the correct data.


    I've written 2 small functions to share that would make this whole ordeal easier to handle:

    function strtodatetime($date, $format = 'Y-m-d H:i:s'){
      return ($d = DateTime::createFromFormat($format, $date)) && $d->format($format) == $date ? $d : false;
    }
    
    function strtounixtime($date, $format = 'Y-m-d H:i:s'){
      return ($d = DateTime::createFromFormat($format, $date)) && $d->format($format) == $date ? $d->getTimestamp() : 0;
    }
    
    echo ($dt = strtodatetime($date)) ? $dt->format($to_format) : 'invalid format';
    echo date('d M, Y h:i:s A', strtounixtime($obj->approve_datetime));
    

    In your scenario, using strtounixtime() (a better strtotime()) it would translate back to the unix epoch if it fails.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流