微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 使用strtotime函数传递错误的日期和时间格式的奇怪行为

我试图理解日期函数strtotime()的以下行为:

> strtotime(1420066800)按预期返回false.
> strtotime(1451602800)返回26197048320!但预计错误为1451602800不是有效的日期和时间格式. (与新的DateTime(1451602800)相同)

我阅读了整个Supported Date and Time Formats页面,但没有找到任何匹配的输入.

顺便说一下,这些是2015-01-01和2016-01-01相对的时间戳.

任何见解将不胜感激.

更新:
不同版本测试结果:

PHP 5.1.6  => false
PHP 5.2.17 => 26197048320
PHP 5.3.29 => 26197048320
PHP 5.4.34 => 26197048320
PHP 5.5.18 => 26197048320
PHP 5.6.2  => 26197048320
PHP 5.6.17 => 26197048320
PHP 7.0.2  => 26197048320

在Mac OS X 10.11.3上运行

让我们从正确的方式开始吧.如果要将时间戳传递给strtotime,则必须在其前面加上“@”.它在 Compound Formats页面的“Localized notations”下解释 – > “Unix时间戳”.
echo(date('r',strtotime('@1420066800'))."\n");
echo(date('r',strtotime('@1451602800'))."\n");

输出是:

Thu,01 Jan 2015 01:00:00 +0200
Fri,01 Jan 2016 01:00:00 +0200

现在,为什么strtotime()为1420066800和26197048320为1451602800返回false?

它期望接收一个字符串,如果它收到一个数字,它不关心并首先将其转换为字符串.然后它遵循一些规则并尝试将日期组件标识到字符串中.因为“1420066800”和“1451602800”都不包含任何组件分隔符,所以它可能会尝试猜测组件的顺序.

今天,2016-02-25,strtotime(‘1451602800′)生成一个时间戳,转换为可打印日期,如下所示:’星期五,25二月2800 14:52:00 0200’

这让我觉得它解释输入字符串如下:14:51:60是时间,2800是年份,其他组件(日,月)是从当前时间初始化的.

文件说:

The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC),relative to the timestamp given in $Now,or the current time if $Now is not supplied.

由于您提供的“日期”不遵循任何有效的日期时间格式,因此strtotime()可以自由返回任何值.它被称为“garbage in,garbage out”.

原文地址:https://www.jb51.cc/php/130490.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐