PHP 的日期使用导致 2 小时错误


PHP's date usage results in 2 hours error

我正在使用date('H:i:s', (time() - $start['time']))来分解自脚本开始以来经过的时间。

无论time() - $start['time']的结果如何 - 无论是 0、17 还是打印出的任何日期,如 02:00:00、02:00:17 等。

可能是什么原因?

time返回一个绝对的数字时间戳,比如2012-06-04 16:35:12的数值。您的开始时间是一个类似的数字,绝对时间戳。从另一个中减去一个将导致一个非常小的数字,这又是一个绝对时间戳。可能是在 1970 年初左右的某个时候。当您使用 date('H:i:s') 格式化该时间戳时,您只显示时间戳的时间部分,如 1970-01-01 02:00:00

了解 UNIX 时间戳的实际含义。

您正在寻找的时差是 time() - $start['time'] ,以秒为单位,您不能简单地使用 date() 格式化。更多内容如下:

$diff = time() - $start['time'];
echo 'Difference in seconds: ' . $diff;
echo 'Difference in minutes: ' . $diff / 60;
echo 'Difference in hours: '   . $diff / 60 / 60;
似乎

您添加了 2H 偏移量。

// save current TZ
$current_tz = date_default_timezone_get();
// Use universal time
date_default_timezone_set('UTC');
$t = time();
echo "T:".$t."<br/>";
sleep(2);
echo "T2: ".date('H:i:s', time() - $t );
// return correct TZ
date_default_timezone_set($current_tz);

如果我在没有 date_default_timezone_set('UTC') 的情况下尝试这段代码,它会给我预期值 + 夏令时 (GMT+1) 的 1H。如果您只需要 2 次之间的差异,则可以对两者使用 UTC,并且只能获得差异,或者您可以检查当前时间偏移量并减去它。

希望对你有帮助