datetime - Age calculation leap year issue in php -
i using following function calculate age given date of birth, not showing correct difference if leap year day i.e 29 used. please me fix 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 can suggest better code please update it.
i need find date of birth in months , days if person less 1 year old.
i having latest 5.4 php version on server.
with 2012-02-29, returning 2 years whereas should 3 years. please help.
why not using date_diff()
function way through? give 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 calculating time difference in seconds , taking 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 day consists of 24 hours each 60 minutes each 60 seconds:
$sday = 60 * 60 * 24;
and calculating years difference be:
$years = floor($diff / (365.2425 * $sday));
but stick first version presented using date_diff()
Comments
Post a Comment