All about PHP/MySQL

Thursday, February 5, 2009

Calculating Age from Date of Birth

In some sections (e.g Profile pages) its nice to display the user's age for the page viewers. Its easier with the following function to calculate age by providing a valid date of birth.

Function:

function GetAge($DOB) {

list($Year, $Month, $Day) = explode("-",$DOB);
$YearDifference = date("Y") - $Year;
$MonthDifference = date("m") - $Month;
$DayDifference = date("d") - $Day;

if ($DayDifference < 0 || $MonthDifference < 0) {
$YearDifference--;
}

return $YearDifference;

}

Usage:

$age = GetAge("1981-05-18"); //Year-Month-Day

echo $age;

Happy Coding :)

3 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home