我有以下代码,打印出两个日期之间的差异:
print_r((new DateTime('2018-01-01'))->diff(new DateTime('2018-11-01')));
print_r((new DateTime('2018-10-01'))->diff(new DateTime('2018-11-01')));
输出:
DateInterval Object
(
[y] => 0
[m] => 10
[d] => 0
[h] => 0
[i] => 0
[s] => 0
[f] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 304
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
DateInterval Object
(
[y] => 0
[m] => 1
[d] => 1
[h] => 0
[i] => 0
[s] => 0
[f] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 31
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
如您所见,第一个日期差正确返回10个月零天。 但是,第二个错误而不是1个月零0天返回,而是错误地返回1个月零1天。
是什么原因造成的?
让我感到困惑的是,我试图在两个PHP沙箱站点上运行此代码,但结果却不一致:
我自己的服务器和https://wtools.io/php-sandbox返回第二天的错误天数。 但是例如,http://sandbox.onlinephpfunctions.com/在第二个日期差中正确返回0天。
答案 0 :(得分:4)
这是因为服务器时区。只需将所有内容设置为UTC,就可以了。
print_r((new DateTime('2018-10-01', new DateTimeZone('UTC')))->diff(new DateTime('2018-11-01', new DateTimeZone('UTC'))));
没有时区,这确实是意外值。 https://3v4l.org/6v0XI