PHP Calculate Age from Date of Birth

in PHP Basics

calendar Sometimes you have a persons date of birth and you want to know age of the person.

With the below snippet you can send it a date and it will return the age as of today's date.

It will first take the date and turn it into a string of a timestamp this is so we can then turn this into a set date format. Having a set format means we can chop up the date and know for sure that what position the day is in, month is in and the year. Once we have these variables then we can work out the difference in the date to work out the age of the person.

function age($date){ $year_diff = ''; $time = strtotime($date);

if(FALSE === $time){ return ''; }

$date = date('Y-m-d', $time); list($year,$month,$day) = explode("-",$date); $year_diff = date("Y") – $year; $month_diff = date("m") – $month; $day_diff = date("d") – $day; if ($day_diff < 0 || $month_diff < 0) $year_diff–; return $year_diff; } [/php]

Subscribe To Newsletter

Get weekly updates to your email