PHP: Proper age calculation

rgbstock.com
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. The first calculates the age kind of manually, and can be used in PHP 4 and PHP 5. The second is a lot shorter and simpler, but requires PHP 5.3.

Enjoy 🙂

// Manual way. Takes unix time stamps.
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;
}

This next function uses the DateTime::diff method available in PHP 5.3.

// Takes dates like 'yyyy-mm-dd'
function getAge($birth, $now = NULL)
{
    $now = new DateTime($now);
    $birth = new DateTime($birth);

    return $birth->diff($now)->format('%r%y');
}

You can test them out at samples.geekality.net/age 🙂