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

To get the number of years between two dates in PHP, you can do the following:

$dt1 = new DateTime('2000-08-07');
$dt2 = new DateTime('2021-08-07');
$diff = $dt2->diff($dt1);
$years = (int) $diff->format('%r%y');

echo $years; // -21

This works in the following way:

  • An instance of DateInterval class is returned as a result of DateTimeInterface::diff();
  • Using the DateInterval::format() method with %y returns the year;
  • Using the DateInterval::format() method with %r format specifier simply adds the "-" sign when the difference is negative;
  • DateInterval::format() returns a string. Therefore, casting the formatted output to an integer helps to ensure the correct type for the year.

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 from DateInterval::format(), 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 using the y property 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.