View Full Version : PHP to determine a person's age
JasonDFR
10-27-2008, 02:41 PM
I have a person's birthdate in MySQL format: YYYY-MM-DD
I would like to determine their age in years.
How can I do this using PHP so I can make comparisons or print it on screen?
Thanks a lot!
JasonD
JasonDFR
10-27-2008, 03:23 PM
I kept working on this after I posted the question and I have come up with this:
function age($year, $month, $day) {
$dob_time_stamp = mktime(0, 0, 0, $month, $day, $year);
$seconds_alive = time() - $dob_time_stamp;
$age = floor($seconds_alive / 31556926);
return $age;
}
Are there any problems with it?
Thanks a lot!
Jason
Medyman
10-27-2008, 11:08 PM
I don't see any problems but I'm not a PHP pro by any means. I just wanted to point you towards this page that shows multiple ways (http://snippets.dzone.com/posts/show/1310)of doing this.
Depending on what you're doing, they might be more useful as you're able to submit a full string (YYYY-MM-DD, etc...) instead of splitting it up. But that all depends on how you have them saved in the first place. Maybe your way makes more sense to your application.
djr33
10-28-2008, 01:39 AM
That seems fine. You might run into slight problems when dealing with leap years, though that's probably not going to be a big problem (you might get someone's age wrong by one year for one day, or something).
Using timestamps as a base is the best, because you can, from those, by design, easily get the date (in various formats), etc.
Using a string is limited because you need to work to parse the string.
Though, I guess, some people are older than 1970, so things might be messy.
JasonDFR
10-28-2008, 07:37 AM
I struggled with the decision of how to store dates of birth in MYSQL.
On one hand unix timestamps are better, on the other hand MySQL's date functions won't work with unix timestamps. I read somethiing that made be decide to go with the MySQL date format for storing dates in MySQL and then worry about changing it in the PHP script.
With that being said, I am not convinced this is the best way to do it. Any suggestions?
I think you can query the MySQL date as UNIX_TIMESTAMP or something, but I am not sure how it returns the timestamp when the date is prior to 1970.
Thanks for looking at this. Any and all comments are appreciated. Especially critical ones.
JasonD
JasonDFR
10-28-2008, 07:53 AM
I just tested this one from dzone and I like it the best. It does take the native MySQL date string as input. Perfect for me.
function get_age( $p_strDate )
{
list($Y,$m,$d) = explode("-",$p_strDate);
return( date("md") < $m.$d ? date("Y")-$Y-1 : date("Y")-$Y );
}
Thanks for the responses!
Jason
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.