How to calculate the age of something according to a date with PHP


Manipulate dates with PHP has become really easy due to the extensive class collections that php offers to handle them. If you don't know how to get the difference in years (and other values ) between 2 given dates, this article may be useful for you.

Calculate the age

The following snippet shows how to retrieve the time difference between a date and now. The diff property of a DateTime object allows you to get a detailed information about the range between the given dates :

  • years ($diff->y)
  • months ($diff->m)
  • days ($diff->days)
  • hours ($diff->h)
  • seconds ($diff->s)
$stringDate = "12/04/1950";
$date = new DateTime($stringDate);
$now = new DateTime();
$interval = $now->diff($date); // the interva contains information about the difference between now and the given date
var_dump($interval);
echo "There are ". $interval->y. " years between the given date and today";

// The output of the var_dump should be something like :

object(DateInterval)#3 (15) {
  ["y"]=>
  int(65)
  ["m"]=>
  int(3)
  ["d"]=>
  int(9)
  ["h"]=>
  int(0)
  ["i"]=>
  int(21)
  ["s"]=>
  int(54)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(1)
  ["days"]=>
  int(23841)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}

Wrapping it in a function

function getDifferenceInYearsBetween($startDate,$limitDate){
  $start = new DateTime($startDate);
  $end = new DateTime($limitDate);
  $interval = $end->diff($start);
  return $interval->y;
}

//call it like 
//month/day/year
echo getDifferenceInYearsBetween("11/19/1997","11/19/2012");

Note: If you're not able to use DateTime class (due to php version 5.2 or something else), you should be able to find the age of something with the following snippet instead :

// Note the format of the string ddate
$birthDate = "12/04/1950";
//explode the date to get month, day and year (careful with the separator character, change it to - if you use that sign)
$birthDate = explode("/", $birthDate);
//get age from date or birthdate
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
? ((date("Y") - $birthDate[2]) - 1)
: (date("Y") - $birthDate[2]));

echo "Age is:" . $age; // 65

As the title of the article, this function limits itself to only the years, however this comes in handy if you have the limitation of the php version.

Become a more social person