Difference between dates in Months for range >= 12

Asked

Viewed 251 times

2

To find the difference between two dates, the date_diff().

$datetime1 = date_create('2016-10-11');
$datetime2 = date_create('2018-10-11');
$interval = date_diff($datetime1, $datetime2);

return $interval->m; // months

The code works perfectly as long as the difference between dates is less than 12. If greater or equal, $interval->m returns 0, but I need it to return the number of months in any case.

Does anyone know any workaround?

1 answer

5


You don’t need workaround, just add 12 months to each year.

return $interval->m + $interval->y * 12;

See working on IDEONE.

Browser other questions tagged

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