PHP date range - wrong month difference

Take a look at this code:

  $first = DateTime::createFromFormat('Y-m', '2001-07');
  $last = DateTime::createFromFormat('Y-m', '1998-06');
  $interval = $first->diff($last);
  echo "m diff: ".$interval->m." y diff: ".$interval->y."\n";

Output m diff: 0 y diff: 3

Why is he returning the wrong month difference?

Interestingly, if I change dates like "2001-08" and "1998-07", it returns the correct monthly interval == 1.

Thanks!

+4
source share
1 answer

PHP DateTimedoes not handle incomplete dates.

DateTime::createFromFormat('Y-m', '2011-07')It is giving DateTime, which has 2011, 7 month and day, hour, minute and second are taken from the current time (at the moment I write this 2011-07-31 18:05:47.

, DateTime::createFromFormat('Y-m', '1998-06') DateTime, 1998, 6, , , ​​, . 31 - , 1998-07-01 18:05:47 (31 1 ).

3 , 0 30 .

2001-08 1998-07 31- , . , , .

, , "Y-m-d H:i:s" "-01 00:00:00" , , createFromFormat, DateTime .

+8

All Articles