Simple but incredibely useful snippet for social networks: Give the date of birth of a person to this function, it will return that person age.
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;
}
Usage
echo 'I am '.age('1982-01-12').' years old';
This will output "I am 28 years old.".

5 Comments
A better implementation of this would convert the incoming $date to a UNIX timestamp using strtotime(), thus eliminating need to have always use age(’2001-10-10′) and could instead support any format supported by strtotime(). Then we generate the Y-m-d based on the UNIX timestamp:
function age($date){
$year_diff = ”;
$time = strtotime($date);
if(FALSE === $time){
return ”;
}
$date = date(‘Y-m-d’, $time);
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;
}
Simply excellent, thanks!
Hi John,
Since you’re already using strtotime, why not just make it a bit easier?
try:
function age($date)
{
$time = strtotime($date);
if(FALSE === $time){
return ”;
}
return floor((mktime() – $time) / 365 / 24 / 60 / 60);
}
Lucas,
That’s a much better implementation. I simply copied/pasted the original snippet to add strtotime() to the mix and didn’t give it much thought. I like yours a lot better
Very nice script but! i enter 1991-03-20 and dine This will output “I am 18 years old” wrong must be 19 years old!
2 Trackbacks
[...] This post was mentioned on Twitter by Jean-Baptiste Jung, tim specht and Clément Roy, PHP Snippets. PHP Snippets said: PHP Snippet: Calculate age of a person using date of birth http://bit.ly/bgBEcw #php [...]
[...] Calculate age of a person using date of birth [...]