Calculate age of a person using date of birth

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

  1. Posted June 28, 2010 at 10:07 pm | Permalink

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

    • Posted June 28, 2010 at 10:53 pm | Permalink

      Simply excellent, thanks!

    • Posted July 20, 2010 at 9:57 am | Permalink

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

      • Posted July 21, 2010 at 5:17 am | Permalink

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

  2. George
    Posted August 2, 2010 at 11:33 am | Permalink

    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

  1. [...] 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 [...]

  2. [...] Calculate age of a person using date of birth [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>