Calculate users age with PHP
Jan 19, 2010 PHP Coding, Web Development
Recently I needed some code to calculate a users age based on their birthday. There are many different functions that are already created out there that I could have used, but instead I wrote this piece of code. It uses PHP 5 DateTime class to return an array of information pertaining to how old a person is. By default if you leave the second parameter off it will calculate the difference from the start date to the current day. If you are trying to calculate how old somebody was when they had passed away or how old they were on a certain date you can pass the second parameter. There are several different checks in this code snippet to make sure you are using a valid date for the start and end date.
This function requires dates to be passed in standard: YYYY-MM-DD format
Code:
if (!function_exists('calculate_age')) { // Checked this function against http://www.timeanddate.com/date/duration.html function calculate_age($startdate = '0000-00-00', $enddate = '0000-00-00') { // Check to see if start date is valid @list($year, $month, $day) = explode('-', $startdate); if (@!checkdate($month,$day,$year)) { return false; } // Create a new datetime object to do our calculations with $s = new DateTime($startdate); // We have to have an end date so if it is empty or 0000-00-00 we will make it right now if (empty($enddate) OR $enddate == '0000-00-00') { $enddate = 'now'; } else { // Check to see if end date is valid @list($year, $month, $day) = explode('-', $enddate); if (@!checkdate($month,$day,$year)) { return false; } } // Create a new datetime object to compare as an end date $e = new DateTime($enddate); if ($s->format('Ymd') > $e->format('Ymd')) { // End date cannot be before start date return false; } // Calculate our base numbers here $years = $e->format('Y')-$s->format('Y'); $months = $e->format('m')-$s->format('m'); $days = $e->format('d')-$s->format('d'); // We cannot have negative days // Calculate how many days are in the startdate month // subtract the startdate day and add 1 // Then add back in the day of the enddate // Subtract 1 month if ($days < 0) { $days = $s->format('t')-$s->format('d')+1; $days += $e->format('d'); $months--; } // We cannot have negative months // Subtract 1 year and add back 12 months to make months positive if ($months < 0) { $years--; $months += 12; } return array('years'=>$years,'months'=>$months, 'days'=>$days); } }
Usage:
// Current date is 2010-01-19 $birthday = '1987-09-23'; $age = calculate_age($birthday); var_dump($age); echo '<hr />'; $startdate = '1985-09-06'; $enddate = '1987-09-23'; $difference = calculate_age($startdate, $enddate); var_dump($difference);
Output:
array(3) { ["years"]=> int(22) ["months"]=> int(3) ["days"]=> int(27) }
——————————————————————————————————–
array(3) { ["years"]=> int(2) ["months"]=> int(0) ["days"]=> int(17) }
Leave a Reply