PHP Function To Work Out Age From Date

1st September 2008

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:

  1. function dateToAge($birthday){
  2. if (($cleaned = strtotime($birthday)) === false){
  3. return false; // Not a readable format
  4. };
  6. list($year, $month, $day) = explode('-', date('Y-m-d', $cleaned));
  7. $age = date('Y') - $year;
  9. if (mktime(0,0,0,$month,$day,date('Y'))
  11. Here is an example of the function in use:
  13. echo '01/20/1980'.birthday('01/20/1980'); // prints 27
  15. 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:
  17. echo '20-01-1979 '.birthday('20-01-1980');
  19. Returns false.
  21. 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.
  23. function dateToAge($birthday){
  24. if (($cleaned = strtotime($birthday)) === false){
  25. if(strpos($birthday,'/')!==false){
  26. $birthday = explode('/',$birthday);
  27. if(count($birthday)==3){
  28. $birthday = $birthday[1].'/'.$birthday[0].'/'.$birthday[2];
  29. };
  30. };
  31. if(strpos($birthday,'-')!==false){
  32. $birthday = explode('-',$birthday);
  33. if(count($birthday)==3){
  34. $birthday = $birthday[1].'-'.$birthday[0].'-'.$birthday[2];
  35. };
  36. };
  37. if (($cleaned = strtotime($birthday)) === false){
  38. return false; // Not a readable format
  39. };
  40. };
  42. list($year, $month, $day) = explode('-', date('Y-m-d', $cleaned));
  43. $age = date('Y') - $year;
  45. if (mktime(0,0,0,$month,$day,date('Y'))

Add new comment

The content of this field is kept private and will not be shown publicly.