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.

PHP:
  1. date_default_timezone_set('America/Los_Angeles');
  2.  
  3. function calculateAge($birthday){
  4.    
  5.     return floor((time() - strtotime($birthday))/31556926);
  6.    
  7. }
  8.  
  9. //USAGE EXAMPLES
  10.  
  11. echo calculateAge('1978-07-11');
  12.  
  13. echo calculateAge('7/11/1978');
  14.  
  15. echo calculateAge('7/11/78');
  16.  
  17. echo calculateAge('July 11, 1978');

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • Reddit
  • Furl
  • NewsVine
  • Simpy
  • Slashdot
  • Spurl
  • StumbleUpon
  • YahooMyWeb
  • TailRank

Home | PHP | PHP Calculate Age