PHP: Calculate Age from DOB
Posted: Sat Mar 17, 2007 6:08 am
Hey guys, since I've spent a fair few hours working on this little snippet, I thought it'd be worth sharing.. as I had to search around for some ideas before I settled on my code:
All dates are in YYYY-MM-DD format, $u['DOB'] and &u['tzOffset'] are values taken from a database containing user data, tzOffset is stored as the offset in hours (i.e. -5 / +2 / -3.5)
The final $m['age'] is the value of the age, also included a check to see whether it's a person's actual birthday, incase you'd like to do anything with that.
Ignore the insane comments... they were for me.
There will be much more elegant ways of doing this, I tried using timestamp difference to begin, though it was late and I couldn't think of the impact leap years would make.
Hope this is useful for someone!
All dates are in YYYY-MM-DD format, $u['DOB'] and &u['tzOffset'] are values taken from a database containing user data, tzOffset is stored as the offset in hours (i.e. -5 / +2 / -3.5)
The final $m['age'] is the value of the age, also included a check to see whether it's a person's actual birthday, incase you'd like to do anything with that.
Ignore the insane comments... they were for me.
Code: Select all
//-- Calculate Age from DOB, times in YYYY-MM-DD FORMAT! --//
$dob = $u['DOB'];
# get user timezone... i.e. what we can take away from server time (GMT/UTC)
$tz = $u['tzOffset'];
# Get date of NOW, unfortunately, server TZ isn't GMT, to make it easier later, convert date INTO GMT here!
$t = time();
# How far in front/behind (of) GMT are we? (i.e. -0500)
$gmtDiff = date("O");
# make this figure usable (we need seconds)
$gmtDiff = ($gmtDiff / 100) * 3600; # here we just turn the -0500 into -5 (-5 hours) then multiply by 3600 (secs per hour =D)
# TRUE GMT TIME NOW?
$t = $t - $gmtDiff;
# User's Timezone offset? (in seconds)
$tz = $tz * 60 * 60;
# User's LOCAL TIME?.. hmm, this could be useful globally?.. yup yup.
$uTime = $t + $tz;
$m['uTime'] = $uTime; // worth noting this is global'ed as a unix timestamp
# Grab both dates as $n and $b (now and birthdate) arrays
$n = explode("-",date("Y-m-d",$uTime));
$b = explode("-",$dob);
# Age step 1, check years..
$age = $n[0] - $b[0];
# Are we BEFORE their birth month?
if ($n[1] < $b[1])
{
$age--;
}
# Are we IN their birth month?
else if ($n[1] == $b[1])
{
# current month / birth month.. are we before, or on their birthday?
if ($n[2] < $b[2])
{
$age--;
}
else if ($n[2] == $b[2])
{
$m['bday'] = "y";
}
}
# Otherwise, we've passed.. or are on their birthday. so the original calc of this year minus birth year is correctimondo =]!
$m['age'] = $age;Hope this is useful for someone!