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…

February 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

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

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

4 thoughts

  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.

  3. rhrff says:

    Nice :)

Comments are closed

Recommended

PHP Day add function

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

November 11, 2009

A new avatar generator for WordPress with get_avatar and Flathash

Brand new avatars for WordPress Gravatar service

April 7, 2017

3 ways to add author’s image in WordPress

Add author's image in WordPress without a plugin

April 5, 2017

Orari trenord, corri solo quando ce n’รจ bisogno

Hai presente quando corri in stazione per prendere il treno al volo e, quando arrivi, ti accorgi che il treno ha 12 minuti di ritardo?

March 30, 2017

Stop sending email to new user in WordPress admin registration

Prevent WordPress to send notification emails when you manually create new users

March 9, 2017

Add Internet Explorer class to body to detect old browser

When you have clients that still uses an old browser, you need to handle it. This javascript function detects the…

February 27, 2017