Calculating age with PHP using a birth date

UPDATED 12/2: Code updated for efficiency and code download link added.

Ran into a problem today– there’s no easy way to add and subtract dates in PHP and be left with standard units (year, month, day, etc), so I whipped up a quick script to do it– the biggest problem is months, here, since PHP deals with second-based timestamps, and months don’t possess a standard number of seconds. Without further ado, here’s the code– I hope it’s helpful to your projects:

//Set the $year, $month, and $day variables to the date you're calculating time since.

/////////////////////////////////////////////////////////////////////
// Calculate age
/////////////////////////////////////////////////////////////////////
//Set your time zone so PHP5 doesn't balk
date_default_timezone_set('America/Denver');
$birthday = strtotime($year.'-'.$month.'-'.$day);
$current_time = time();
$curr['month'] = date('n', $current_time);
$curr['lastmonth'] = $curr['month'] - 1;
$curr['year'] = date('Y', $current_time);
$curr['lastyear'] = $curr['year'] - 1;
$curr['day'] = date('j', $current_time);

//get the time difference in seconds
$diff = $current_time - $birthday;
$age['years'] = intval($diff/31556926);
//get the remaining seconds
$diff = $diff - (31556926 * $age['years']);
//Now for the tricky part-- number of months
if($curr['month'] > $month) {
$age['months'] = $curr['month'] - $month;
if($curr['day'] < $day) { $age['months']--; $month_temp = strtotime($curr['year'].'-'.$curr['lastmonth'].'-'.$day); } else { $month_temp = strtotime($curr['year'].'-'.$curr['month'].'-'.$day); } //Get the remaining seconds $diff = $current_time - $month_temp; } elseif($curr['month'] == $month) { if($curr['day'] >= $day) {
$age['months'] = 0;
//since months are 0, we don't need to alter diff
} else {
$age['months'] = 11;
//Get the remaining seconds
$month_temp = strtotime($curr['year'].'-'.$curr['lastmonth'].'-'.$day);
$diff = $current_time - $month_temp;
}
} else {
$age['months'] = $curr['month'] - $month + 12;
if($curr['day'] < $day) { $age['months']--; $month_temp = strtotime($curr['year'].'-'.$curr['lastmonth'].'-'.$day); } else { $month_temp = strtotime($curr['year'].'-'.$curr['month'].'-'.$day); } $diff = $current_time - $month_temp; } //calculate days $age['days'] = intval($diff/86400); //get the remaining seconds $diff = $diff - (86400 * $age['days']); //calculate hours $age['hours'] = intval($diff/3600); //get the remaining seconds $diff = $diff - (3600 * $age['hours']); //calculate minutes $age['minutes'] = intval($diff/60); //get the remaining seconds $diff = $diff - (60 * $age['minutes']); //and we're left with seconds $age['seconds'] = $diff; print_r($age);

Or you can download the source file here, if you're having copy/paste troubles.

Leave a Reply

Your email address will not be published. Required fields are marked *