joshtronic

in Software Development #PHP

Calculate Age from Date with PHP

Calculating the age based on a date is a pretty simple task that can be accomplished many different ways (Google yield's quite a few different approaches). The caveat that usually arises is that you need to factor in which side of the birthday you are on based on the day's date. What I mean is, using myself as the example, I was born on February 23rd. From January 1st to the 22nd of 2013 I was 31 years old. From the 23rd of February until February 22nd, 2014 I will be be 32 years old. To accomplish this you will need to determine what date it is and calculate the difference accordingly:

$birthday           = '1981-02-23';
$today              = date('Y-m-d');
list($y1, $m1, $d1) = explode('-', $birthday);
list($y2, $m2, $d2) = explode('-', $today);
$m1                 = $m2 - $m1;

if ($m1 < 0 || ($m1 == 0 && $d2 - $d1 < 0)) { $y1++; }

$age = $y2 - $y1;

Sorry about the abbreviated variable names, generally not my style but thought it was be just as confusing using $dob_year and $today_year. Okay, maybe it wouldn't have been so bad. The gist is depending if the current date is before or on / after the birthday, offset the year before calculation.

There is a significantly shorter (but not nearly as accurate in my opinion) way to calculate the age:

$age = floor((time() - strtotime($birthday)) / 31556926);

The value 31556926 is the equivalent of 365.242190 days, or what we consider to be a full year (factors in leap day and such). Fact is, time is relevant and we could get into a whole debate over the exactly length of a year. This shorter solution will get you the right answer and I'm actually unsure under what scenario it would falter (it would only be for part a day when it does though).

Now these are both great examples if you're using a PHP version before 5.3 which introduced the date_diff() function which is simply an alias for DateTime::diff() but with significantly reduced syntax. As both were introduced in 5.3, there's no reason to use the longer syntax (and I won't be discussing it). To get the age all you need is:

$datetime = date_diff(date_create(), date_create($birthday));
$age      = $datetime->format('%Y');

Okay, so it's a bit longer than the previous example, but it also give you the flexibility to return more than just the year. With the format() object function (or date_format() if you'd rather pass the $datetime object as an argument) you could get how many years, months, days, hours, minutes and seconds old someone is. Could come in handy if you had a website for your child and wanted to calculate how many months old they are for the first year (or 2 as most people seem to do).