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

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.…

November 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…

November 11, 2009

Count coloured cells on Google Sheets with reference

In a spreadsheet if you need to count cells based on their background you can use this code in Google…

May 22, 2020

WP doesn’t send email? try this

Snippets for sending emails with Wordpress

February 8, 2020

Two post types share the same taxonomy in WordPress

Sharing a WordPress taxonomy between two post types is useful especially if you want to create a relation between different…

November 14, 2019

MYSQL add counter in a query

Use mysql variables to create a counter in SQL, PHP code to use an SQL counter and what does the i mean in mysqli?

November 9, 2019