PHP: Proper age calculation
Published:
Always struggle with calculating age in PHP for some reason. And there seems to be quite varying ideas on how this should be done. So decided to once and for all sit down and figure out how I could do this.
Found an article which explained pretty well why I was a bit confused. It also had a code example in Perl(?).
So, thought I could stick a PHP version here in case that page dies or I forget. Actually there are two versions. The first calculates it manually and can be used in PHP 4 and PHP 5, while the second uses DateTime::diff
and requires PHP 5.3 or later.
Manual calculation
/**
* Calculates age by using... math.
*
* @author Torleif Berger
* @link http://www.geekality.net/?p=1397
* @link http://00f.net/2007/06/04/an-age-is-not-a-duration/
*
* @param timestamp date of birth, 'yyyy-mm-dd'
* @param timestamp now, 'yyyy-mm-dd'. defaults to `time()`
* @return number the age
*/
function getAge($birth, $now = NULL)
{
$now = getdate($now === NULL ? time() : $now);
$birth = getdate($birth);
$age = $now['year'] - $birth['year'];
if($now['mon'] < $birth['mon']
|| ($now['mon'] == $birth['mon'] && $birth['mday'] > $now['mday']))
{
$age -= 1;
}
return $age;
}
Using DateTime::diff
/**
* Calculates age by using diff function.
*
* @author Torleif Berger
* @link http://www.geekality.net/?p=1397
* @link http://www.php.net/manual/en/datetime.diff.php
*
* @param string date of birth, 'yyyy-mm-dd'
* @param string now, 'yyyy-mm-dd'. defaults to `time()`
* @return number the age
*/
function getAge($birth, $now = NULL)
{
$now = new DateTime($now);
$birth = new DateTime($birth);
return $birth->diff($now)->format('%r%y');
}