PHP calculate age
I'm looking for a way to calculate the age of a person, given their DOB in the format dd/mm/yyyy.
I was using the following function which worked fine for several months until some kind of glitch caused the while loop to never end and grind the entire site to a halt. Since there are almost 100,000 DOBs going through this function several times a day, it's hard to pin down what was causing this.
Does anyone have a more reliable way of calculating the age?
//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));
$tdate = time();
$age = 0;
while( $tdate > $dob = strtotime('+1 year', $dob))
{
++$age;
}
return $age;
EDIT: this function seems to work OK some of the time, but returns "40" for a DOB of 14/09/1986
return floor((time() - strtotime($birthdayDate))/31556926);
PHP
- asked 8 years ago
- Gul Hafiz
5Answer
This works fine.
<?php
//date in mm/dd/yyyy format; or it can be in other formats as well
$birthDate = "12/17/1983";
//explode the date to get month, day and year
$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;
?>
- answered 8 years ago
- G John
$date = new DateTime($bithdayDate);
$now = new DateTime();
$interval = $now->diff($date);
return $interval->y;
- answered 8 years ago
- Gul Hafiz
$tz = new DateTimeZone('Europe/Brussels');
$age = DateTime::createFromFormat('d/m/Y', '12/02/1973', $tz)
->diff(new DateTime('now', $tz))
->y;
As of PHP 5.3.0 you can use the handy DateTime::createFromFormat
to ensure that your date does not get mistaken for m/d/Y
format and the DateInterval
class (via DateTime::diff
) to get the number of years between now and the target date.
- answered 8 years ago
- Gul Hafiz
Simple method for calculating Age from dob:
$_age = floor((time() - strtotime('1986-09-16')) / 31556926);
31556926
is the number of seconds in a year.
- answered 8 years ago
- G John
If you want to caculate the Age of using the dob, you can also use this function. It uses the DateTime object.
function calcutateAge($dob){
$dob = date("Y-m-d",strtotime($dob));
$dobObject = new DateTime($dob);
$nowObject = new DateTime();
$diff = $dobObject->diff($nowObject);
return $diff->y;
}
- answered 8 years ago
- G John
Your Answer