Page 1 of 1

Quick and cheap PHP age function Rate Topic: -----

#1 gm04030276  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 20
  • Joined: 06-January 08

Posted 09 March 2010 - 04:56 AM

A function I developed after following a tutorial somewhere on the web that used a lot more code!
Thought I would share for your use/appreciation/criticism

function get_age($uts){
	$t = time();
	if(date('z', $t) < date('z', $uts)){ $rtr = ((date('Y', $t) - 1) - date('Y', $uts)); }
	else{ $rtr = (date('Y', $t) - date('Y', $uts)); }
	return $rtr;
}



It takes a unix timestamp as input.

The first line sets the current unix timestamp because we're using it 6 times and want it to be the same...and i'm sure it's faster not to have to work it out each time, yes?

The second line checks to see if the current day of this year ('z' is day of year) is less than the day of the year on which the person's birthday falls. If it is less, meaning they haven't had their birthday yet, then we set the return value as this year minus the year they were born minus an extra one because their birthday hasn't happened yet.

The third line only happens if their birthday has happened this year in which case this year minus the year they were born will be their correct age so we set that as the return value.

And finally, simply return the age we calculated.

You could easily shorten this to 3 lines even if you put the return keyword in place of $rtr = in the if/else code blocks.

Enjoy! :)

Is This A Good Question/Topic? 0
  • +

Page 1 of 1