Why are you not using the date_diff()
function all the way through? it will give you the desired result:
function getAbsAge($birthday) {
$age = '';
$diff = date_diff(date_create(), date_create($birthday));
$years = $diff->format("%y");
$months = $diff->format("%m");
$days = $diff->format("%d");
if ($years) {
$age = ($years < 2) ? '1 Year' : "$years Years";
} else {
$age = '';
if ($months) $age .= ($months < 2) ? '1 Month ' : "$months Months ";
if ($days) $age .= ($days < 2) ? '1 Day' : "$months Days";
}
return trim($age);
}
Another way would be by calculating the time difference in seconds and taking it from there:
list($year,$month,$day) = explode("-", $birthday);
$diff = mktime(0,0,0,date('n'),date('j'),date('Y')) - mktime(0,0,0,$month,$day,$year);
Then a day consists of 24 hours each with 60 minutes each with 60 seconds:
$sday = 60 * 60 * 24;
And then calculating the years difference would be:
$years = floor($diff / (365.2425 * $sday));
But i would just stick to the first version i presented you using date_diff()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…