Sometimes you’ll need to calculate an age. It could be the age of a member on your website… It could be your cat. Either way, this can be useful for a variety of reasons such as personalized messages, criteria-based marketing or any functionality that is based on age demographics. I’ve seen a few different versions of this function – some of them even returning incorrect values! – and I’ve found that this one seems to be the most reliable version.
<?php
/* calculate a person's age. */
function jCalculateAge($sDateStamp) {
$oDate = strtotime($sDateStamp);
$sDate = date("Y-m-d", $oDate);
list($iYear, $iMonth, $iDay) = explode("-", $sDate);
return date("md") < $iMonth . $iDay ? date("Y") - $iYear - 1 : date("Y") - $iYear;
}
?>
This function accepts one argument and can be any acceptable version of a date stamp. For example, 08/31/1986, August 31, 1986 and 1986-08-31 will all work.
There have been many improvements to this function including: more strict validation, date of death, supporting the December-January divide, and even converting the age to a human-readable format such as “1 month, 15 days”. Alternate versions of this function can be found at snippets.dzone.com.
Tags: Awesome, Nyan Cat, PHP