Home    Articles

 

How to get the AGE of a person related to current date or a specific date in PHP

 

/**
* get age by birthdate
* $birthDate format = YYYY-MM-DD
* $currentDate format = YYYY-MM-DD
*/
function getAge($birthDate = '1800-01-01',$currentDate = '') {
	//explode the date to get month, day and year
        $currentYear = (!empty($currentDate))? date('Y',strtotime($currentDate)):date('Y');
        $currentMD = (!empty($currentDate))? date('md',strtotime($currentDate)):date('md');
	$birthDate = explode("-", $birthDate);
        $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[1], $birthDate[2], $birthDate[0]))) > $currentMD? (($currentYear - $birthDate[0]) - 1) : ($currentYear - $birthDate[0]));
	return $age;
}

This is how you can get a persons age related to current date or a specific date. In case you want to see how old was someone 5 years ago on a specific date.

The returned values is in ages, not an exact number or string like: 3 years, 5 months and x days.

It should be quite useful.

by