Why in this code at the output is the result?

$datetime1 = date_create('2014-03-01'); $datetime2 = date_create('2014-03-31'); $interval = date_diff($datetime1, $datetime2); echo $interval->format('%Y %m %d'); ---- 00 1 2 ---- 

Where did 2 days come from?

change the starting date a bit:

 $datetime1 = date_create('2014-03-02'); $datetime2 = date_create('2014-03-31'); $interval = date_diff($datetime1, $datetime2); echo $interval->format('%Y %m %d'); ---- 00 0 29 ---- 

only +1 day have been added, and not 1 month and 2 days, but 0 month and 29 days ...

  • Look at the result of your code execution: ideone.com/TLjUlJ The only thing I can advise is to try to write like this: $ interval = date_diff ($ datetime1, $ datetime2, true); In addition, you did not take 2, but 3 extra days. - VenZell
  • added true, nothing interesting happened. By the way, if you specify the date, for example, 2014-01-01 and 2014-02-01, you will get exactly 0 years, 1 month and 0 days. all other dates are crooked ... 2014-03-01 and 2014-04-01 = 0god 1month 2dya 2014-03-01 and 2014-04-02 = 0godn 1month 1dnya ... ept well, how can that be? )) - youstm
  • The behavior is really strange. For example, for the same numbers in January we get the correct value 00 0 30 . And if you change the timezone, for example, to 'America / New_York', the above code begins to be considered correctly. As a solution, get the number of days $ interval-> format ('% a'); and already process the received value independently - vanchester

1 answer 1

It seems I managed to get to the bottom of the truth. I think this code will explain the reason (the time zone is set as Europe / Moscow)

 $sourceDate = strtotime('2014-03-01'); echo date('Ym-d', $sourceDate),"\n"; // 2014-03-01 echo gmdate('Ym-d', $sourceDate),"\n"; // 2014-02-28 $sourceDate = strtotime('2014-03-31'); echo date('Ym-d', $sourceDate),"\n"; // 2014-03-31 echo gmdate('Ym-d', $sourceDate),"\n"; // 2014-03-30 

The date increment is in UTC. Here is an example of implementing date_diff in php:

 function date_diff($date1, $date2) { $current = $date1; $datetime2 = date_create($date2); $count = 0; while(date_create($current) < $datetime2){ $current = gmdate("Ymd", strtotime("+1 day", strtotime($current))); $count++; } return $count; } 

Therefore, as a solution to the problem, you can change the code to:

 $datetime1 = date_create('2014-03-01 00:00:00 +00'); $datetime2 = date_create('2014-03-31 00:00:00 +00'); $interval = date_diff($datetime1, $datetime2); echo $interval->format('%Y %m %d'); 

And we get the correct difference

  • thank. But there are bugs ((for example, dates: 2014-03-01 and 2014-05-01, it gives the result 0 1 30, it turns out not 2 months, but 1 month and 30 days, which is not right. It turns out, I need to do a cycle and find out how many days in the month for my date intervals ((( youstm
  • @ test, corrected solution - vanchester