简体   繁体   English

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

[英]strtotime returns different results on different PHP versions

I came across a weird problem with strtotime function returning different (and I think incorrect) results. 我遇到了一个奇怪的问题,即strtotime函数返回了不同的结果(我认为是不正确的)。

This is my test code and results: 这是我的测试代码和结果:

$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)

You can see it live on http://codepad.org/gdTqFLqG . 您可以在http://codepad.org/gdTqFLqG上实时查看它。
Do you have any idea why is this happening? 您知道为什么会这样吗?

I agree with @NB's suggestion to use the DateTime class instead -- You shouldn't really be using strtotime() for this kind of thing today. 我同意@NB建议改用DateTime类-今天您不应该真的将strtotime()用于这种事情。

However, as for why it's happening, look at the dates you're comparing.... what often happens between those dates? 但是,为什么会发生这种情况,请查看您比较的日期。...这些日期之间经常发生什么? Yep, that's right -- daylight savings. 是的,没错-夏令时。

So my guess is that it's got nothing to do with the PHP version, and more to do with the timezone setup on the different platforms you're testing. 所以我的猜测是,它与PHP版本无关,而与要测试的不同平台上的时区设置无关。 One is set to use the UCT and the other is set to use a local timezone that has DST. 一个设置为使用UCT,另一个设置为使用具有DST的本地时区。

您应该使用date_default_timezone_set(),因为在第二次测试中您通过一些UTC +-校正获得了正确的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM