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
DateIntervalclass is returned as a result of
- Using the
%yreturns the year;
- Using the
%rformat 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
%rformat specifier from
trueas 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
Hope you found this post useful. It was published . Please show your love and support by sharing this post.