Tuesday, February 9

Get Age From Birthday

function GetAge($Birthdate){

// Explode the date into meaningful variables
list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate);

// Find the differences
$YearDiff = date("Y") - $BirthYear;
$MonthDiff = date("m") - $BirthMonth;
$DayDiff = date("d") - $BirthDay;

// If the birthday has not occured this year
if (($MonthDiff < 0) || ($MonthDiff == 0 && $DayDiff < 0))
$YearDiff--;
return $YearDiff;
}
Shamelessly stolen from:
Geekpedia

edited: apparently neither
($MonthDiff >=0 && $DayDiff >= 0)
nor
($DayDiff < 0 || $MonthDiff < 0)
were taking all the math correctly into account. We managed to figure out something better.

2 comments:

James Harr said...

Nice and simple, though the condition for the day-of-year was inverted.

if (!($DayDiff < 0 || $MonthDiff < 0))
$YearDiff--;

// De Morgan it up.
if ($MonthDiff >=0 && $DayDiff >= 0)
$YearDiff--;

tygrr said...

Nice, thanks :)