问题
I am using following function to calculate age from given date of birth, but its not showing the correct difference if a leap year day i.e 29 is used. Please help me fix this code.
<?php
function getAbsAge($birthday)
{
list($year,$month,$day) = explode("-", $birthday);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 || $month_diff < 0)
{
$year_diff--;
}
if ($year_diff == 0)
{
$interval = date_diff(date_create(), date_create($birthday));
$months = $interval->format("%M");
$days = $interval->format("%d");
if ($months > 0)
{
return $interval->format("%M Months %d Days");
}
else if ($months == 0 && $days > 1)
{
return $interval->format("%d Days");
}
else
{
return $interval->format("%d Day");
}
}
else if ($year_diff == 1)
{
return "$year_diff Year";
}
else if ($year_diff > 1)
{
return "$year_diff Years";
}
}
echo getAbsAge("2012-02-29")
?>
Also if anyone can suggest a better code then please update it.
I need to find date of birth in months and days if a person is less than 1 year old.
I am having latest 5.4 php version on my server.
With 2012-02-29, its returning 2 Years whereas it should be 3 Years. Please help.
回答1:
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()
来源:https://stackoverflow.com/questions/29317183/age-calculation-leap-year-issue-in-php