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;


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 and 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:


    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


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

Corri solo quando ce ne รจ bisogno

Sono un pendolare sui treni delle Ferrovie Nord, tutti i giorni vado avanti e indietro tra Cusano e Milano. I…

March 27, 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

Add filter on wp_title not working with Yoast SEO plugin

For SEO purposes, in a specific template that has a list of items with pagination, I need to have different…

February 22, 2017

Generate all old PDF preview images with WordPress 4.7

WordPress 4.7 generates thumbnails for PDF files while uploading them in the media library, this is a really good thing…

December 13, 2016