【问题标题】:PHP strtotime(): date showing '1970-01-01 ' after conversionPHP strtotime():转换后显示“1970-01-01”的日期
【发布时间】:2018-05-04 12:14:17
【问题描述】:

我正在从 Excel 表中读取数据并插入 MySQL 表中。在这个过程中,我使用 PHP 方法strtotime() 将时间戳(字符串)转换为日期时间。

$timestamp = date('Y-m-d H:i:sa',strtotime(trim($value->Time)));

这在某些情况下会失败。

例子:

 echo date('Y-m-d H:i:s',strtotime('04-13-2018 0:00:53'));

 echo date('Y-m-d H:i:s',strtotime('04-12-2018 0:00:53'));

输出:

1970-01-01 00:00:00

2018-12-04 00:00:53

谁能帮我解决这个问题?

失败的示例字符串:

04-12-2018 0:00:53
04-12-2018 0:01:53
04-12-2018 0:02:53
04-12-2018 0:03:53
04-12-2018 0:04:53
04-12-2018 0:05:53
04-12-2018 0:06:53
04-12-2018 0:07:53
04-12-2018 0:08:54
04-12-2018 0:09:54
04-12-2018 0:10:53
04-12-2018 0:11:53
04-12-2018 0:12:53
04-12-2018 0:13:53
04-12-2018 0:14:53
04-12-2018 0:15:53
04-12-2018 0:16:53
04-12-2018 0:17:53
04-12-2018 0:18:53
04-12-2018 0:19:54
04-12-2018 0:20:54
04-12-2018 0:21:54
04-12-2018 0:22:53
04-12-2018 0:23:54
04-12-2018 0:24:53
04-12-2018 0:25:54

【问题讨论】:

    标签: php mysql datetime


    【解决方案1】:

    您的格式不是format that the parser understands

    在您的情况下,13 不是“月”。所以解析器至今无法理解。

    你应该使用DateTime::createFromFormat():

    $date = DateTime::createFromFormat('m-d-Y H:i:s','04-13-2018 0:00:53');
    echo $date->format('Y-m-d H:i:s');
    

    输出:

    2018-04-13 00:00:53
    

    请注意,格式也可以是:'m-d-Y G:i:s'G 表示“没有前导零的小时的 24 小时格式”

    【讨论】:

    • 知道了。刚才,我想通了并修复了它。无论如何,感谢您的即时回复。
    • 就是你用了-来表示位置,phpstrtotime()-解析成d-m-y,和m/d/y是等价的。
    • 另外,@Syscall,如果你看一下逻辑,13 绝不意味着一个月。所以这很荒谬。
    • 我知道我的格式不是有效格式,但为什么函数 date('format',false) 给我的日期是 1970 年?为什么不返回 false 或 undefined?
    • @Andrea_86,在documentation中定义,第二个参数是一个整数,所以,你的false值被解释为0。时间戳 0 的日期是 unix 时间戳 (1970)。
    【解决方案2】:

    strtotime() 和(我不记得技术术语)“美式格式”值的字符串格式错误:

    echo date('Y-m-d H:i:s', strtotime('04-13-2018 0:00:53'));
    echo date('Y-m-d H:i:s', strtotime('04/13/2018 0:00:53'));
    

    https://3v4l.org/Qnsru

    给予:

    1970-01-01 01:00:00
    2018-04-13 00:00:53
    

    基本上,您给了strtotime()(它叫什么?)“欧洲日期时间”值。 - 表示 day 是第一部分,而不是 month

    这是很久以前的事了。

    【讨论】:

      【解决方案3】:

      添加到已经回答的内容。
      您得到 1970 的原因是因为 strtotime 如果无法解析日期,则返回 false。
      而 0(假)unix 时间是 1970 年。

      【讨论】:

        猜你喜欢
        • 2012-02-17
        • 2011-09-09
        • 2016-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多