Find how many years are between two dates in PHP
To find how many years are between two given dates, use the DateTime()
, diff()
, and format()
functions.
Example:
Count how many years are between two given dates in PHP.
<?php
$firstDate = new DateTime("2010-01-01");
$secondDate = new DateTime("2022-01-01");
$yearsBetween = $secondDate->diff($firstDate)->format("%y years");
echo $yearsBetween;
?>
Output: 12 years.
Example 2:
Count how many years, months, and days are between two given dates in PHP.
<?php
$firstDate = new DateTime("2010-01-01");
$secondDate = new DateTime("2022-05-04");
$yearsBetween = $secondDate->diff($firstDate)->format("%y years %m months %d days");
echo $yearsBetween;
?>
Output: 12 years 4 months 3 days
Years between dates PHP function
If you want ready-to-implement solution that you can use in many places in your code, you can use the function like this one:
<?php
function yearsBetweenDates($date1, $date2, $format) {
$firstDate = new DateTime($date1);
$secondDate = new DateTime($date2);
return $secondDate->diff($firstDate)->format($format);
}
// Examples:
echo yearsBetweenDates("12.04.2011", "25.12.2015", "%y years"); // Output: 4 years
echo yearsBetweenDates("12.04.1990", "25.12.2015", "%y years %m months and %d days"); // Output: 25 years 8 months and 13 days
?>