PHP DateTime差返回错误的天数
作者:互联网
我有以下代码,打印出两个日期之间的差异:
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沙箱站点上运行此代码,但结果却不一致:
我自己的服务器和https://wtools.io/php-sandbox在第二个日期返回了错误的天数.
但是例如http://sandbox.onlinephpfunctions.com/在第二个日期差中正确返回0天.
解决方法:
这是由于服务器时区.只需将所有内容设置为UTC,就可以了.
print_r((new DateTime('2018-10-01', new DateTimeZone('UTC')))->diff(new DateTime('2018-11-01', new DateTimeZone('UTC'))));
如果没有时区,则确实是意外的值. https://3v4l.org/6v0XI
标签:php-7-2,php 来源: https://codeday.me/bug/20191024/1924313.html