* Thus wrote John Ryan ([EMAIL PROTECTED]): > Hi, > hello ryan, > In mySQL, I store dates as YYYY-MM-DD, a standard DATE type. It stores users > date of births. I need to calculate in a PHP script, the users age from this > DOB. I get a PHP date in the same format as the mySQL and subtract, which > returns the year rounded off. ie, it doesnt matter if your birthdays in june > of 1983 and the date is januray 2003, your age is still returned as 20, when > it should be 19. > > Does anyone know how can i get the right age?
To get a real age of someone you would use seconds, but since the actual count of seconds get messed up on leap years (through the convertion from seconds to years), I approached it with the method most people calculate ages. Most people first look at the year and find the differnce, then if the month/day hasn't come around you subtract one; alas the common calculation for age. Here is the code to demonstrate that logic: $dob = split('-', '1980-12-1'); $now = split('-', date('Y-m-d')); // we are either this age or one less $age = $now[0] - $dob[0]; // have we gotten to the month of in dob? if ($now[1] < $dob[1]) { // no, so we are technically a year less. $age--; // If we're in the month, has the day come yet? } elseif ($now[1] = $dob[1] && $now[2] < $now[3]) { // no, still a few more days. $age--; } // your age is proper, in day to day usage. /* Note: instead of the if () elseif() you can use if (mktime(0,0,0,$now[1],$now[2]) < mktime(0,0,0,$dob[1],$dob[2])) { $age--; } */ HTH, Curt -- "I used to think I was indecisive, but now I'm not so sure." -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php