PHP 中的日期函数总是给出晚一天的日期

Date function in PHP gives always date one day behind

我的情况是,日期总是晚一天。 例如,我有这个值 -243219600 是相对于日期 18/04/1962

经过

date('d/m/Y', -243219600);

输出为:

17/04/1962

-243219600 秒从 1970 年 1 月 1 日起 00:00:00 UTC 在 javascripthere 你得到正确的日期。

检查您 PHP 的时区,将其设置为与您的计算机相同(因为您使用 javascript)。

date() 的输出取决于配置的时区。如果您添加时间和时区,您可以看到它。在我的例子中是 CET:

echo date('d/m/Y H:m:i T', -243219600);
//prints: 18/04/1962 00:04:00 CET

date()

的解决方案

如果要date()使用UTC,请使用date_default_timezone_set:

date_default_timezone_set('UTC');
echo date('d/m/Y H:m:i T', -243219600);"

输出

 17/04/1962 23:04:00 UTC

(你看,因为现在是 UTC 午夜前一小时,日期取决于时区)

DateTime的解决方案:

DateTime class 如果它是由 Unix 时间戳构造的,则始终使用 UTC:

来自documentation:

Note:

The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

所以你也可以使用下面的代码:

echo (new DateTime('@-243219600'))->format('d/m/Y');