RSS Feed for Urbano's Blog

Calculate age in PHP from timestamp

If you ever wanted to calculate someone's age in PHP from a birth timestamp, you must take into account that the age is more than the number of years, since days and months are also important, so I wrote a simple function that will return the exact age for a given timestamp:

 
function getAge($birth){
	$t = time();
	$age = ($birth < 0) ? ( $t + ($birth * -1) ) : $t - $birth;
	return floor($age/31536000);
}
 

Basically we first get the current time and store it in a variable (To avoid having to call the function time more than once)
Then we get the age in milliseconds (Taking into account that before 1969 timestamps are negative, thus the ternary operator)

Now we have the date in milliseconds, we divide it by the number of milliseconds in a year (60*60*24*365)

And that is basically it :)

Spread the word!

  • Digg
  • StumbleUpon
  • Reddit
  • del.icio.us
  • Technorati
  • DZone
  • MySpace
  • Mixx
  • TwitThis
  • Facebook

This entry was posted on Tuesday, September 8th, 2009 at 4:26 pm and is filed under PHP, Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Reply comments
Reply comments