How to Get Number of Months Between Two PHP DateTime Objects?

When you calculate the difference between two PHP DateTime objects, it returns a DateInterval object. From this DateInterval object, you can access the year and month to calculate the total months between two dates like so:

$start = new DateTime('2020-01-01 00:00:00');
$end = new DateTime('2021-03-15 00:00:00');
$diff = $start->diff($end);

$yearsInMonths = $diff->format('%r%y') * 12;
$months = $diff->format('%r%m');
$totalMonths = $yearsInMonths + $months;

echo $totalMonths; // 14

Using the DateInterval::format() method with %y and %m format specifiers, you get the year and month respectively. The %r format specifier, simply adds the "-" sign when the difference is negative. To test this you switch the $end and $start dates to see a negative time period:

$start = new DateTime('2020-01-01 00:00:00');
$end = new DateTime('2021-03-15 00:00:00');
$diff = $end->diff($start);

$yearsInMonths = $diff->format('%r%y') * 12;
$months = $diff->format('%r%m');
$totalMonths = $yearsInMonths + $months;

echo $totalMonths; // -14

If you do not wish to include the negative sign for negative time periods, you can do either of the following:

  • Simply remove the %r format specifier when retrieving the year and month, or;
  • Pass true as the second argument to the DateTime::diff() method to always return an absolute / positive interval.

Instead of using the DateInterval::format() method, you can also directly access the year and month values using the y and m properties on the DateInterval object. Similarly, to check for a negative time period, you can access the invert property (which equals 1 if the interval represents a negative time period and 0 otherwise).


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.