April 9th, 2005
Calculating a person’s age
Here’s a quick guide to calculating a person’s age in PHP:
<?php
function calculateAge($birth)
{
$now = time();
$ageInSeconds = $now - $birth;
$age = $ageInSeconds / (60 * 60 * 24 * 365);
$age = floor($age);
return $age;
}
?>
This is all pretty straight-forward. We first subtract the current time with the time of birth. Notice that PHP deals with time in seconds since the UNIX epoch (January 1st, 1970). Therefore we have have to divide with (60 * 60 * 24 * 365), which is the amount of seconds in a year. Then we round the number down, because we don’t want decimals.
To determine the correct PHP-style timestamp for a specific date, PHP provides some useful conversion functions. You can read more about them in the PHP manual. Here’s an example:
<?php
$birth = strtotime("1980-01-01");
$age = calculateAge($birth);
echo "Mr. Foo Bar is ".$age." years old.";
?>
I don’t know how this function performs with all this leap year and daylight saving time weirdness, but it should be sufficient in most cases.