PHP Calculate Age
This is the simplest way I could devise to calculate a person's age. Basically I calculate the input variable and use strtotime() to convert it to a timestamp. I chose this method to give the most flexibility in the input. Then I simply calculate the difference in seconds and divide that by the number of seconds in a year. You should probably add some validation to be sure the input date is before today, but again, this is quick and dirty.
You’re currently reading “ PHP Calculate Age ,” an entry on BRADINO
- Published:
- 11.6.07 / 5pm
- Category:
- PHP























pro!
Thanks a lot
Thank you!! :-)
nice and quick :)
tnx
Code does not work because it is based on a time stamp which only accounts for years from 1970 to present day, so anyone born before then will be calculated based on a birthday of 1/1/1970.
tnx bro…
The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. PHP 5.1.0 and newer versions overcome this limitation though.
Good day,
Assumption 1: birth dates are usually stored without time.
Assumption 2: age is usually calculated as of midnight on the birthday.
Given these assumptions, the way that your function handles leap years (by using 31556926 seconds for a year) causes unexpected results:
floor((strtotime(”2009-03-10″) – strtotime(”2008-03-10″))/31556926) would return 0 instead of the expected 1.
Obviously, simply using 31536000 does not solve the problem either.
function getAge($day, $month, $year)
{
// define age
$age = date(’Y') – (int) $year;
// month not yet passed
if((int) $month > date(’m')) $age–;
// month == this month
elseif(date(’m') == (int) $month)
{
// day has yet to come
if((int) $day > date(’j')) $age–;
}
return $age;
}
ps: your comment post thingy makes one – out of 2 – signs ;)
function getAge($month, $day, $year) {
if(checkdate($month, $day, $year) !== FALSE) {
list($m, $d, $y) = explode('/', date('m/d/Y'));
return ($month <= $m && $day <= $d) ? ($y - $year) : ($y - $year - 1);
}
return 0;
}
Great work!!
Erik and Ryan, your codes don’t work. The one posted is easily the most accurate here even if it does have the potential to throw errors on the odd occasion.