1

I recently discovered a strange behavior of DateTime diff(). I just tried to calculate the difference between the following dates:

$first = new DateTime('2016-07-05T00:00:00');
$second = new DateTime('2016-12-30T23:59:59');
$interval = $first->diff($second);
echo $interval->h;

The strange thing is that this will output:

-1

That's a little bit confusing as I thought the public attributes of DateInterval are positive. Now if I try to create such a DateInterval by myself:

$interval = new DateInterval('P5M26DT-1H59M59S');

This will fail as negative values for hours are not allowed.

Is this behavior normal? If yes, how can i safely convert a DateInterval to string/from string (e.q. for storing in a DB)?

Dom
  • 11
  • 2
  • 1
    You have a daylight savings shift in that timeframe don't you – Mark Baker Dec 05 '16 at 13:13
  • Yeah i think thats the issue! If the first date is inside the daylight saving time, the problem occurs. But nevertheless shouldn't PHP smart enough to decrease the amount of dates by 1 and increase the hours by 24, so we get a positive hours value again? – Dom Dec 05 '16 at 13:48
  • My guess would be that more people would complain if the days value wasn't what they expected than if the hours value was -1 – Mark Baker Dec 05 '16 at 14:10
  • Did you get this result in Linux SO? – Gabriel Heming Dec 05 '16 at 15:44
  • Thank you for your answers. Yes i used Linux, but i think this will occur on every OS. I think i know understand why the -1 is necessary. See http://www.mendoweb.be/blog/php-dateinterval-dst-change/ – Dom Dec 05 '16 at 17:53

0 Answers0