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 :)
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:
Thanks for this... been trying to sort it and then browsing webto see what i was doing wrong and this one is the one thats working after i've altered it slightly to fit in with my site's db :)
By Steve, At March 27, 2011 at 7:41 AM
Wow..awesome! this code works perfectly! there is alot of tutorial ive seen but this one is simplest and easy to understand! Great Job!
By Ralph Tan, At August 13, 2012 at 8:04 PM
Excellent work !!!
By Ikram, At March 22, 2017 at 5:12 AM
Post a Comment
Subscribe to Post Comments [Atom]
<< Home