19 September, 2010

Get age from birthdate using php the easiest way

Once i had a situation to get age of a user from his/her birthdate. After some testing, i managed to work it out. Following
code is used to get age from date. I hope this might help someone like me.

//date in mm/dd/yyyy format; or it can be in other formats as well
$birthDate = "08/14/1972";
//explode the date to get month, day and year
$birthDate = explode("/", $birthDate);
//get age from date or birthdate
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[1], $birthDate[0], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])):(date("Y")-$birthDate[2] - 1));
echo "Age is:".$age;


Anonymous said...

This script is incorrect. It thinks that 15/12/1990 is 20 not 19 years old.

Sudhir Bastakoti said...

Thanks for showing my mistake, it's changed and is working now. The parameters passed to mktime were wrong.
Thanks again

Anonymous said...

Hi, I tested this and think it is incorrect. Using today's date as the birthdate along with the year 1980, it should return 31, but it in fact returns 30.

Sudhir Bastakoti said...

Thanks for pointing out my mistake. I've resolved this problem. Should work as expected now. Try it once.

Jack said...

Still not working properly, used DOB of 07/14/1981 and returns 29 not 30.

Can you explain what is the problem with script?
Thank you!