PHP Calculate Age

This is the simplest way I could devise to calculate a person's age. Basically I calculate the input variable and use strtotime() to convert it to a timestamp. I chose this method to give the most flexibility in the input. Then I simply calculate the difference in seconds and divide that by the number of seconds in a year. You should probably add some validation to be sure the input date is before today, but again, this is quick and dirty.

date_default_timezone_set('America/Los_Angeles');

function calculateAge($birthday){
   
    return floor((time() - strtotime($birthday))/31556926);
   
}

//USAGE EXAMPLES

echo calculateAge('1978-07-11');

echo calculateAge('7/11/1978');

echo calculateAge('7/11/78');

echo calculateAge('July 11, 1978');

  • Digg
  • TwitThis
  • del.icio.us
  • Netvouz
  • description
  • Reddit
  • Furl
  • NewsVine
  • Simpy
  • Slashdot
  • Spurl
  • StumbleUpon
  • YahooMyWeb
  • TailRank
  • Technorati
  • Facebook
  • Google
  • LinkedIn
  • Live
  • MySpace
  • Ping.fm
  • Yahoo! Buzz
  • E-mail this story to a friend!



Home | PHP | PHP Calculate Age