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.
Why are you not using the
date_diff()
function all the way through? it will give you the desired result:Another way would be by calculating the time difference in seconds and taking it from there:
Then a day consists of 24 hours each with 60 minutes each with 60 seconds:
And then calculating the years difference would be:
But i would just stick to the first version i presented you using
date_diff()