$year = date('Y', strtotime("2012"));
var_dump($year);//returns 2013
这发生在一台装有 php 5.2 的旧服务器和一台装有 php 5.4 的新服务器上
服务器使用 strtotime 从类似 2012-01-01
或 2012-01
或 2012
的字符串中获取年份
我还尝试使用 $dt = new DateTime('2012')
然后 getTimestamp
返回“1374516720”,即“Mon, 22 Jul 2013 18:12 :00 格林威治标准时间”
是什么导致了这个错误?在documentation它说 strtotime 只接受年份
我不知道该怎么办...
编辑:
$year = date('Y', strtotime("2012"));
被视为军事时间,当年 20:12
最佳答案
使用完整的日期字符串 YYYY-MM-DD
和 01.01
作为日期对我来说是个窍门:
$year = date('Y', strtotime("2012-01-01"));
var_dump($year);//returns 2012
通常我建议按照@Rufinus 的建议使用DateTime::createFromFormat()
,但是该方法在PHP5.2 中不可用(您在其中一台服务器上使用的)。也许是升级旧版本的原因? ;)
发生这种情况的原因:
虽然manual在某一点上说 YYYY
(并且只是 YYYY)格式是可以的,它在下面的几行中说明了对该行为的限制: strtotime()
called with YYYY
将在特殊情况下返回今天 20:12 的时间戳:
The "Year (and just the year)" format only works if a time string has already been found -- otherwise this format is recognised as HH MM.
我不知道他们说已经找到时间字符串
是什么意思。但是您可以使用以下行看到此行为:
var_dump(date("Y-m-d H:i:s", strtotime('2012')));
// output: string(19) "2013-07-22 20:12:00"
这导致结果 2013
。
关于php - 解析年份时 strtotime 和 DateTime 给出错误的年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17785443/