PHP: Proper age calculation
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 πŸ™‚

  • hmm

    It doesn’t work properly

    • Works properly as far as I can see in my sample. Examples would kind of help πŸ˜‰

  • ball

    you should validate user input. it breaks when you put an invalid date into the box.

    • Doesn’t matter. The point here isn’t bullet-proof date fields in a form.

  • Ezequiel Lauria

    ΒΏDoes it work with leap years?

    • Not sure why leap years would make any difference in the way this calculation is done? All I can say is do a test and see what happens πŸ™‚ Let me know if you find something interesting πŸ™‚