computing age from mySQL date

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
hlamster
Forum Newbie
Posts: 2
Joined: Wed Dec 08, 2010 11:39 am

computing age from mySQL date

Post by hlamster »

I have a date retrieved from mySQL and am trying to compute a persons age.

$p1DOBphp = strtotime($p1DOB);
$p1Age = date() - $p1DOBphp;
$p1AgeYr = DATE('Y',$p1Age);

where $p1DOB is the Date Of Birth in a SQL date format (i.e. yyyy-mm-dd)

But I get weird results. What am I doing wrong.

Thanks/Hal
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: computing age from mySQL date

Post by AbraCadaver »

Code: Select all

$p1AgeYr = ( time() - $p1DOBphp ) / 31556926;
//or
$p1AgeYr = floor( ( time() - $p1DOBphp ) / 31556926 );
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
hlamster
Forum Newbie
Posts: 2
Joined: Wed Dec 08, 2010 11:39 am

Re: computing age from mySQL date

Post by hlamster »

Works like a charm. Thanks.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: computing age from mySQL date

Post by AbraCadaver »

hlamster wrote:Works like a charm. Thanks.
Since I forgot to explain:

You are taking the birthdate as number of seconds since 1970/01/01 and subtracting the current date as number of seconds since 1970/01/01, resulting in the difference in seconds. So divide that by the number of seconds in 1 year to get the number of years.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply