strtotime在不同的PHP版本上返回不同的结果


strtotime returns different results on different PHP versions

我遇到了一个奇怪的问题,strtotime函数返回不同的(我认为是不正确的)结果。

这是我的测试代码和结果:

$fromTime = strtotime('2013-10-22');
$toTime = strtotime('2013-10-28');
$days = ($toTime - $fromTime) / (3600 * 24);
var_dump($days, $fromTime, $toTime);
// PHP 5.2.5 on codepad.org - correct
// int(6)
// int(1382400000)
// int(1382918400)
// PHP 5.3.15, PHP 5.4.6 - incorrect I guess
// float(6.0416666666667)
// int(1382392800)
// int(1382914800)

你可以看到它的直播http://codepad.org/gdTqFLqG.
你知道为什么会发生这种事吗?

我同意@N.B.的建议,改为使用DateTime类——今天你不应该真的使用strtotime()来做这种事情。

然而,至于为什么会发生这种情况,看看你正在比较的日期。。。。两次约会之间经常发生什么?是的,没错——夏令时。

所以我的猜测是,这与PHP版本无关,更多的是与您正在测试的不同平台上的时区设置有关。一个被设置为使用UCT,另一个被设定为使用具有DST的本地时区。

您应该使用date_default_timezone_set(),因为在第二次测试中,您得到了正确的时间,并进行了一些UTC+校正。