$a = new DateTime("2023-05-31", new DateTimeZone('Europe/Rome'));
$b = new DateTime("1970-05-31", new DateTimeZone('Europe/Rome'));
var_dump($a->diff($b)->y);
// int(52)
$a = new DateTime("2023-05-30", new DateTimeZone('Europe/Rome'));
$b = new DateTime("1970-05-30", new DateTimeZone('Europe/Rome'));
var_dump($a->diff($b)->y);
// int(53)
Why in the first case the diff is 52?
I expect 53 for both cases
3
Answers
The difference in the results of PHP’s date_diff() function for the two sets of dates with the same timezone can be explained by the way the function calculates the difference between two DateTime objects.
When you calculate the difference between two dates using date_diff(), the function considers the number of full years between the two dates. It does not take into account the exact number of days or any fractional parts of a year.
In the first case:
The difference between May 31, 2023, and May 31, 1970, is exactly 52 full years. Even though the dates are not the same day, the function calculates the difference based on the number of years.
In the second case:
The difference between May 30, 2023, and May 30, 1970, is also exactly 53 full years. However, since the dates are the same day, the function calculates the difference based on the exact number of days and recognizes the additional full year.
So, in the first case, the function calculates the difference as 52 years because it only considers the full years, whereas in the second case, it recognizes the additional full year due to the dates being the same day.
There seems to be something about Italy in general. Possibly they didnt do a Summer time one year that is confusing the function (Thats a guess)
RESULTS
Found this on
https://www.timeanddate.com/time/change/italy/rome?year=1970
which may go some way to explain.Tested it myself, and I noticed something interesting. As I mentioned in my comment, there was a 1 hour difference between the 31st dates, but then I noticed this:
As you can see, on the 31st, there’s a 2 hour offset, but on the 30th, there’s a 1 hour offset. Checking with https://www.timeanddate.com/time/zone/italy/rome , the time changed on May 31st, 1970 at 12:00 am, so the 12am hour didn’t actually exist, and it jumped to 1am. The comparison does a full comparison, and so the difference is actually
52y 11m 30d 23:00:00.0