我正在尝试做一些非常基本的时间数学 - 基本上,给定时间和距离输入,计算速度。我选择使用 strtotime() 将时间输入转换为秒 - 但我得到了一些奇怪的结果。
例如,给出这个示例程序:
<?php
$t1 = strtotime("3:15:00",0);
$t2 = strtotime("1:00:00",0);
$t3 = strtotime("2:00:00",0);
$t4 = strtotime("9:00:00",0);
echo $t1 . "\n";
echo $t2 . "\n";
echo $t3 . "\n";
echo $t4 . "\n";
?>
为什么我会得到这些结果?
$ php test.php
-56700
-64800
-61200
-36000
更新:
既然没人明说,那我就解释一下上面函数的bug吧。我曾假设将零时间传递给 strtotime() 会导致它生成从午夜派生的时间戳,1969 年 12 月 31 日,UTC - 这听起来很奇怪,但可以满足我的目的。
我没有想到的是 strtotime() 在转换字符串时会考虑时区,而我的服务器显然比 UTC 晚 5 小时。最重要的是,由于时区转换,PHP 然后将时间解释为相对于 纪元前一天 这意味着它将我的时间解释为相对于 12 月 30th, 1969 而不是 31, 导致负数...
看来 Eugene 是正确的 - 如果我只想计算耗时,我不能使用内置的时间函数。
最佳答案
如果你想做类似的事情,我想你只想对时间字符串本身做一些数学运算并将它们转换为秒数,如下所示:
<?php
function hmstotime($hms)
{
list($hours, $minutes, $seconds) = explode(":",$hms);
return $hours * 60 * 60 + $minutes * 60 + $seconds;
}
?>
关于php - PHP 时间数学的奇怪行为 : Why is strtotime() returning negative numbers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1061472/