4

I would like to calculate the difference between two DateTime objects. It works, except if the clock is adjusted between the two times. For example:

date_default_timezone_set("Europe/Berlin");

// create start date
$start = \DateTime::createFromFormat('Y-m-d H:i:s', '2018-03-24 06:00:00');

// set the end date to the same time on the next day
//$end = \DateTime::createFromFormat('Y-m-d H:i:s', '2018-03-25 06:00:00');
$end = clone $start;
$end->modify('+1 day');

// calculate diff
$diff = $start->diff($end);

// print results
print_r(array(
    "start" => $start,
    "end" => $end,
    "diff" => (new DateTime())->setTimeStamp(0)->add($diff)->getTimeStamp() / 3600
));

On march 25 at 2AM the clock is advanced to 3AM, so the difference between 2018-03-24 06:00:00 and 2018-03-25 06:00:00 should be 23, but the result is 24. Why do I get the wrong result, and how is it possible to fix it?

Iter Ator
  • 8,226
  • 20
  • 73
  • 164

0 Answers0