date_diff returns incorrect difference

Asked

Viewed 68 times

0

I was doing some tests with this function, but it returns an incorrect difference, as I do to get around it?

Example: when compared the difference between day 01/01 with 01/03 return the difference of a month, and only when it is day 04/03 return the two months.

Correct:

$datetime1 = new DateTime('2009-01-01');
$datetime2 = new DateTime('2009-03-04');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
echo $interval->format('%R%m month');

Upshot:

+62 days+2 Month


Incorrect:

$datetime1 = new DateTime('2009-01-01');
$datetime2 = new DateTime('2009-03-01');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
echo $interval->format('%R%m month');

Upshot:

+59 days+1 Month

  • 2

    The Dateinterval::format() method does not recalculate carry over points in time strings nor in date Segments. This is expected because it is not possible to overflow values like "32 days" which could be Interpreted as Anything from "1 Month and 4 days" to "1 Month and 1 day".From the PHP manual

1 answer

0


The Dateinterval::format() method does not recalculate transport points in time sequences or in date segments. This is expected because it is not possible to exceed values such as "32 days", which could be interpreted as something from "1 month and 4 days" to "1 month and 1 day". Manual for PHP

Browser other questions tagged

You are not signed in. Login or sign up in order to post.