Calculate Age

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Calculate Age

Post by SidewinderX »

I have a birthday in the form yyyy-mm-dd how can I convert that to an age?

Say I have a string

Code: Select all

$dob = "1988-10-10";
How can I calculate the age from that?


Thanks.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

I wrote this a long time ago, the code is kind of nasty but it does the job..

viewtopic.php?t=50354
User avatar
mikeeeeeeey
Forum Contributor
Posts: 130
Joined: Mon Jul 03, 2006 4:17 am
Location: Huddersfield, UK

Post by mikeeeeeeey »

Look at it logically, you need to take the current date and assess it from the string $dob

A really simple way, which would need working on would be to take sub strings from a string, and then do a bit of maths, so:

Code: Select all

$year = (int)substr($dob,0,4); //takes the year out

$thisYear = date(Y);

$age = $thisYear - $year;
Then you could build the months into this to be completely sure.

Hope that helps!
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

If the data is in a mysql table, you can calculate age in your sql query:

Code: Select all

SELECT ....
	YEAR(NOW()) - 
		YEAR(dob) - 	
		(DATE_FORMAT(NOW(), '%m%d') < DATE_FORMAT(dob, '%m%d')) 
	AS age
FROM...
Post Reply