Page 1 of 1

Calculate age from DOB

Posted: Tue Aug 18, 2009 8:24 pm
by mikes1471
Hi everyone, I have done a search on this topic and the closest I came to generating my date of birth on a webpage was out by a whole 9years lol (I'm 30 not 39)

I have user data stored in a database which includes $birthdate in a YYYY/MM/DD format, using Juma929's code as below:

Code: Select all

# $dob = strtotime($birthdate);
# $date_today = strtotime(date("Y/m/d"));
#  
# $agex = $date_today - $dob;
#  
# $years = floor($agex / 31556926);
# $remainder = $agex % 31556926;
# $months = floor($remainder / 2592000);
#  
# echo $years . ' ' . $months;
As i say this produced 39years old.

I'd just like some clues as to where its gone wrong or a prefered snippest of code to use.

Ive called the $birthdate info in my code

Code: Select all

$birthdate = mysql_query("SELECT birthdate FROM users WHERE id='$id'");
$birthdatearray = mysql_fetch_assoc($birthdate);
$dob = strtotime($birthdate);
$date_today = strtotime(date("Y/m/d"));
  
$agex = $date_today - $dob;
  
$years = floor($agex / 31556926);
$remainder = $agex % 31556926;
$months = floor($remainder / 2592000);
 
echo $years . ' ' . $months;
Any suggestions welcome

Re: Calculate age from DOB

Posted: Tue Aug 18, 2009 8:42 pm
by jackpf
If you store the DoB in a unix timestamp it would a lot easier.

Something like this?

Code: Select all

 
$dob = 'drawn from the database';
 
$difference = time() - $dob;
 
$age = floor($difference / 60 / 60 / 24 / 30 / 12);
 

Re: Calculate age from DOB

Posted: Tue Aug 18, 2009 9:01 pm
by John Cartwright
Heres the method I've come to use (the 2nd example). See http://ma.tt/2003/12/calculate-age-in-mysql/

Re: Calculate age from DOB

Posted: Tue Aug 18, 2009 9:03 pm
by Eran
another option is to use what I suggested in a recent thread - viewtopic.php?f=1&t=104720&p=559851