What’s your age? PHP can tell you

Posted on Mar 7, 2008 in PHP |


I was looking around for a simple function or something that calculates the age of a person with a given date. I figured there must be something that did this natively in PHP, but to my surprise…. no.

Further looking around found some overly complicated (not “complicated” but just way too long for what they do) scripts to calculate an age. In the spirit of easy minimal code, I did it in two lines :

$ageTimestamp = time() - strtotime($date);
$age = floor($ageTimestamp/60/60/24/365);

So…. quick explanation for those that are learning the ropes ….

Line 1 : $date is what you want to determine the age from. This can be any sort of date that converts with strtotime() into a timestamp, which is basically any kind of valid date format. What we do in the first line is get the current date as a timestamp, and then subtract the timestamp of the date we want. What we get as a result is the number of seconds between the two dates, therefore, the age in seconds.

Line 2 : We then use the value we got from line 1 and get the number of years those seconds translate to. To do this you just divide your time in seconds by 60(seconds in a minute) then 60(minutes in an hour) then 24(hours in a day) and finally 365 (days in a year). Finally, you use the floor() method to round that number down to the nearest integer and voila! You now have the number of years since that date.

You can take this further and make it a function or whatever. For example:

public function getAge($date){
	$ageTimestamp = time() - strtotime($date);
	return floor($ageTimestamp/60/60/24/365);
}