douyi6922 2016-11-10 23: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-10 23: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部