I have the following code, which prints out differences between two dates:
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')));
Output:
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
)
As you can see, the first date difference returns correctly 10 months and 0 days. The second one however, instead of returning 1 month a 0 days, returns incorrectly 1 month and 1 days.
What is causing this?
What baffles me, is that I tried to run this code on couple of PHP sandbox sites and I am getting inconsistent results:
My own server and https://wtools.io/php-sandbox returns the wrong amount of days for the second date. But for example http://sandbox.onlinephpfunctions.com/ returns correctly 0 days on the second date difference.
This is because of server time zones. Just set everything as UTC and you should be alright.
https://3v4l.org/PWKiD
Without the timezone, it is indeed the unexpected value. https://3v4l.org/6v0XI