Feb 10 2010

PHP how to calculate age from date of birth

Category: PhpGiulio Pons @ 10:59 am

This is a very simple script that starts from a string date in format yyyy-mm-dd and return the age.
To do this it splits the date, calculate years with difference from current year and the fix the value based on difference between months and days from current date:

// input $date string format: YYYY-MM-DD
function age($date){
	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;
}
Share

Related posts:

  1. PHP find previous monday from a date
  2. PHP Day add function
  3. PHP bot to grab meteo information from Google
  4. Calculate dir size recursively with PHP (and count files)
  5. get MySpace events with a PHP function

Tags: , ,

3 Responses to “PHP how to calculate age from date of birth”

  1. nbanba says:

    age(“1994-04-27″);

    I’m 16, but this function shows only 15 :D

  2. Giulio Pons says:

    Really? :D it needs a fix.

Leave a Reply