PHP how to calculate age from date of birth

This is a very simple script that starts from a string date in format yyyy-mm-dd and return the age. To…

Febbraio 10, 2010

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;
}

Author

PHP expert. Wordpress plugin and theme developer. Father, Maker, Arduino and ESP8266 enthusiast.

Comments on “PHP how to calculate age from date of birth”

4 thoughts

  1. nbanba ha detto:

    age(“1994-04-27”);

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

  2. Giulio Pons ha detto:

    Really? :D it needs a fix.

  3. rhrff ha detto:

    Nice :)

Comments are closed

Recommended

Force WordPress to use Italian date

To get date with get_the_time in Italian you should specify italian (it_IT) in the WP_LANG constamt in your wp_config.php file.…

Novembre 21, 2014

PHP Day add function

How to add 2 days to a date in PHP? There are many ways to add days to a string…

Novembre 11, 2009

The Quantcast CMP broke my sites

A javascript error in CMP blocks my site.

Maggio 19, 2023

WP Gutenberg notes

Collection of notes and thoughts on Wordpress Gutenberg blocks development.

Gennaio 9, 2023

Optimizing LCP, Largest Contentful Paint result

Notes about Core Web Vitals optimization challenge

Gennaio 4, 2023