Skip to content
Advertisement

PHP’s date_diff() is behaving unexpectedly

It’s probably just me being dumb, but …

JavaScript

in PHPfiddle gives (as expected):

object(DateInterval)#3 (15)
{ [“y”]=> int(0)
[“m”]=> int(1) <=== this is what gives me problems on my local machine
[“d”]=> int(0)
[“h”]=> int(0)
[“i”]=> int(0)
[“s”]=> int(0)
[“weekday”]=> int(0)
[“weekday_behavior”]=> int(0)
[“first_last_day_of”]=> int(0)
[“invert”]=> int(0)
[“days”]=> int(30)
[“special_type”]=> int(0)
[“special_amount”]=> int(0)
[“have_weekday_relative”]=> int(0)
[“have_special_relative”]=> int(0) }

Check out the value of m, which is number of months.

However, on my local machine, the same code gives:

JavaScript

OK, I will concede that is is 30 days, but the answer that I was looking for was 1 month, and $interval->m is zer0.

What am I missing? I don’t know what version of PHP the PHPfiddle web site uses, but I am using 7.3.11 locally.

Advertisement

Answer

Probably the difference is in the timezone.

try this:

JavaScript

also try this:

JavaScript

Probably date_diff looking for a difference between UTC timestamp and you have the default timezone on your PHP set to some positive value.

Let’s say you have some default timezone which is UTC+02:00 therefore date_create('2019-11-01') actually makes a date 2019-10-31 22:00:00 (UTC) and date_create('2019-12-01') actually makes a date 2019-11-30 22:00:00 (UTC)

now you can see they have no whole month difference.

But you can catch another funny effect:

JavaScript

Also you may have unexpected result if your timezone has the daylight saving.

JavaScript

PHPFiddle has the default timezone set to UTC, therefore it gives one month difference by default.

To avoid that, just perform all date calculations in UTC from the beginning:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement