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 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) {

return $YearDifference;



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

echo $age;

Happy Coding :)


  • 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 Anonymous 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 Anonymous Ralph Tan, At August 13, 2012 at 8:04 PM  

  • Excellent work !!!

    By Blogger Ikram, At March 22, 2017 at 5:12 AM  

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home