Aug 3, 2009

PHP: calculating age with no bugs

As it turns out, calculating a person's age is not a very simple thing to do.

I've been very lazy lately so I googled for a PHP or MySQL function to calculate age in years. The more I searched, the more I found out that people were doing it wrong.

For example: floor(time_difference_in_days) / 356, let's say 7000/356 = 19,66.

What the hell? That won't work. We have leap years and such.

And even worse: some calculated the difference in days with strtotime() or mktime() that uses unix timestamps, which is very unfortunate for people born before 1970-01-01. (if you don't know why, read the wiki)

I decided to do this the way that we humans do it. It's commented and streched out for a reason. Stop doing it wrong.
function age($dob) {
//year, month, day of birth
 list($y, $m, $d) = explode('-', $dob);
//this year,month, day
 list($yn, $mn, $dn) = explode('-', date('Y-m-d'));

//AGE is (THIS_YEAR - YEAR_OF_BIRTH) if the person already had or is having his birthday THIS_YEAR
 $age = $yn - $y;

//If the person didn't have his birthday yet, then AGE is (THIS_YEAR - YEAR_OF_BIRTH - 1)
 if ($mn < $m) {
//THIS_MONTH is less than MONTH_OF_BIRTH so no birtday yet this year!    
  $age--;
 } else {
//if it's the same MONTH_OF_YEAR then the birthday did not occur only if THIS_DAY_OF_MONTH is less than DAY_OF_BIRTH    
  if ($mn == $m) {
   if ($dn < $d) {
    $age--;
   }
  }
 }
 return $age;
}

No comments: