Mj Jam
Mj Jam

Reputation: 173

convert date value in mysql into age

I have a table in the databse named myTable and inside the table there is a row named myBirth , I inserted inside mybirth row date value which is stored as a DATETIME.

and I want to know how to convert the date value in mysql into age and then echo it. I saw similar questions but I still get an error in my code.

$result = 'SELECT myBirth (YEAR, CURDATE()) AS age FROM myTable';
$run = mysql_query($result);  

while($row = mysql_fetch_array($run))
{
$age = $row['myBirth']; 
}
echo  $age;  

Upvotes: 0

Views: 300

Answers (2)

Harsha Jayamanna
Harsha Jayamanna

Reputation: 2258

Write an "SQL function" as "myBirth". And pass the values (YEAR and CURDATE()) ). Do the calculations inside the function and return the age.

example "myBirth" function.

SET @d1 = YEAR, 
SET @d2 = CURDATE()

SET @d3 = DATEDIFF(@d1,@d2) 

RETURN  @d3;

This example only gives an idea about wht to do.

Upvotes: 1

user557846
user557846

Reputation:

http://www.artfulsoftware.com/infotree/queries.php#96

Age in years Given a birthdate in @dob, here are two simple formulae for age in years:

Date_format( From_Days( To_Days(Curdate()) - To_Days(@dob) ), '%Y' ) + 0

Year(Curdate()) - Year(@dob) - ( Right(Curdate(),5) < Right(@dob,5) )

and here is one for age in years to two decimal places, ignoring day of month:

Round((((Year(now()) - Year(@dob)))*12 + (((Month(now()) - Month(@dob)))))/12, 2)

Upvotes: 0

Related Questions