PHP Function To Work Out Age From Date

Use the following function to work out how many years have passed since an event. This can be useful if you want to work out a persons age based on their birthday.

The function works by standardising the format of the date using the PHP strtotime() function. This is the first step of the function and sorts out if the date is valid or not. Once this has been done then the date is formatted into a standard form of yyyy-mm-dd, which is then split using the explode() function. The year of the inputted date is then subtracted from the current year, giving the age in years. A final check makes sure that the date hasn't passed yet, and subtracts one from the years value to give a more accurate result. Here is the function:

function dateToAge($birthday){
 if (($cleaned = strtotime($birthday)) === false){
  return false; // Not a readable format
 };
 
 list($year, $month, $day) = explode('-', date('Y-m-d', $cleaned));
 $age = date('Y') - $year;
 
 if (mktime(0,0,0,$month,$day,date('Y')) < mktime()){
  // Birthday hasn't passed, so subtract one year from age
  $age--;
 };
 
 return $age;
}

Here is an example of the function in use:

echo '01/20/1980'.birthday('01/20/1980'); // prints 27

There is one issue with this function is you cannot be sure that the date will be in a standard format. Some cultures put the date as day/month and others put it as month/day. This can make the function return nothing, even though the date is correct. So the following:

echo '20-01-1979 '.birthday('20-01-1980');

Returns false.

The following function sorts this problem out by trying to clean up the date entered so that it can be recognised by the program if it initially isn't a valid date.

function dateToAge($birthday){
 if (($cleaned = strtotime($birthday)) === false){
  if(strpos($birthday,'/')!==false){
   $birthday = explode('/',$birthday);
   if(count($birthday)==3){
    $birthday = $birthday[1].'/'.$birthday[0].'/'.$birthday[2];
   };
  };
  if(strpos($birthday,'-')!==false){
   $birthday = explode('-',$birthday);
   if(count($birthday)==3){
    $birthday = $birthday[1].'-'.$birthday[0].'-'.$birthday[2];
   };
  };
  if (($cleaned = strtotime($birthday)) === false){
   return false; // Not a readable format
  };
 };
 
 list($year, $month, $day) = explode('-', date('Y-m-d', $cleaned));
 $age = date('Y') - $year;
 
 if (mktime(0,0,0,$month,$day,date('Y')) < mktime()){
  // Birthday hasn't passed, so subtract one year from age
 $age--;
 };
 
 return $age;
}

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.