PHP getting difference between two dates in years and months
<?php
function differenceInYearsMonths($date1, $date2)
{
// change $format
// as per your server
// date format
$format = 'Y-m-d';
$diff = DateTime::CreateFromFormat($format, $date2)->diff(DateTime::CreateFromFormat($format, $date1));
return $diff->y . ' year(s) & ' . $diff->m . ' month(s)';
}
// 4 year(s) & 0 month(s)
var_dump(differenceInYearsMonths('2015-06-11', '2019-06-11'));
// 21 year(s) & 1 month(s)
var_dump(differenceInYearsMonths('1998-05-22', '2019-06-22'));
// 12 year(s) & 10 month(s)
var_dump(differenceInYearsMonths('1997-12-31', '2010-10-31'));
differenceInYearsMonths() will be of great use for things like Professional experience where you display difference between two dates in years and months.