How to calculate a person's age using an SQL formatted input date
by Matt J. Whetham, October 2010
A fairly simple procedure - calculate age from an SQL formatted date (YYYY-MM-DD) - or so I thought. In my haste to develop an application for a customer's website, rather than creating a function myself, I figured I would do a quick Google search for a prewritten function that someone perhaps may have posted. Usually something like this will take approximately 2 minutes max to seek out, implement, and test to ensure that it works fine.
Not in this case.
To my dismay, the functions that I found all lacked a proper method of determining the age based on TODAY. They forgot to calculate one less year if the birthday had not yet passed this year.
So alas, here is a proper PHP function for calculating the age of someone today, using a SQL formatted input date:
<?php function getAge($sqlDate) { // Convert SQL date to individual Y/M/D variables list($Y,$m,$d) = explode("-",$sqlDate); $age = date("Y") - $Y; // If the birthday has not yet come this year if(date("md") < $m.$d ) { $years--; } return $years; } ?>
Then of course, to echo it out:
<?php $date_of_birth = "1970-12-01"; echo getAge($date_of_birth); // Returns correct age based upon today's date ?>
Local: (705) 812-6288
Toll-free: 1-877-WHETHAM (1-877-943-8426)
E-mail: sales@whethamsolutions.com
Address: 11 Victoria St. Unit A5, Barrie, ON