我有以下代码,打印出两个日期之间的差异:
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个月零天.
但是,第二个返回而不是0天返回1个月,而是错误地返回了1个月零1天.
是什么原因造成的?
让我感到困惑的是,我试图在几个PHP沙箱站点上运行此代码,但结果却不一致:
解决方法:
这是由于服务器时区.只需将所有内容设置为UTC,就可以了.
print_r((new DateTime('2018-10-01', new DateTimeZone('UTC')))->diff(new DateTime('2018-11-01', new DateTimeZone('UTC'))));
标签:php-7-2,php
来源: https://codeday.me/bug/20191024/1924313.html