Calculate age from DOB

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
mikes1471
Forum Commoner
Posts: 88
Joined: Sat Jan 24, 2009 3:29 pm

Calculate age from DOB

Post 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
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Calculate age from DOB

Post 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);
 
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Calculate age from DOB

Post by John Cartwright »

Heres the method I've come to use (the 2nd example). See http://ma.tt/2003/12/calculate-age-in-mysql/
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Calculate age from DOB

Post by Eran »

another option is to use what I suggested in a recent thread - viewtopic.php?f=1&t=104720&p=559851
Post Reply