Hi,
I have a table which has peoples details in, one field is DOB.
When the persons details are viewed i would like to have their age displayed aswell, this will have to calculated "on the fly" as i don't want to store it in the table.
My date format is "16-Dec-2003" and its not a date field in mysql, just a standard text.
Is this someting that PHP can do?
Can anyone help me out?
Thanks
Stephen
Calculate Age from DOB
Moderator: General Moderators
-
stephenp222
- Forum Newbie
- Posts: 3
- Joined: Sun Dec 28, 2003 5:21 am
Why isn't it a date-field when there's a date in?
Nevertheless you can use mysql's date/time functions as long as mysql can cast it to a date/time value. And it has a function DATEDIFF(expr,expr2) that returns the difference between two dates in days, e.g.
SELECT DATEDIFF(dob, Now()) FROM myTable WHERE id=5
Nevertheless you can use mysql's date/time functions as long as mysql can cast it to a date/time value. And it has a function DATEDIFF(expr,expr2) that returns the difference between two dates in days, e.g.
SELECT DATEDIFF(dob, Now()) FROM myTable WHERE id=5
-
stephenp222
- Forum Newbie
- Posts: 3
- Joined: Sun Dec 28, 2003 5:21 am
you're trying to open another php-block within a php-block
what's in the field dob? the "day of birth"-date or the student-id? unlikely that it is both.
After you've figured that out you have to use mysql_query() to send the statement to the mysql-server and fetch the result with e.g. mysql_fetch_array()
Code: Select all
$sqlwrk = 'SELECT DATEDIFF (`dob`, Now()) FROM `details` WHERE dob=' . $x_student_id;After you've figured that out you have to use mysql_query() to send the statement to the mysql-server and fetch the result with e.g. mysql_fetch_array()
i created a function for that... if your dates are stored close enough, you can use it without modification. otherwise, here's something forr you to play with to get that. (this is a simple enough thing that i don't see any point in wasting time tryin to get you there since others have ad there's been no feedback stating how far you've gotten)
Code: Select all
function findAge ($dob){
$year=substr($dob,0,4); $month=substr($dob,5,2); $day=substr($dob,8,2); # get year, month, day from dob
$today = localtime();
$age = ($today[5]+1900) - $year; // this can be a year to old!
if ($month < ($today[4]+1)) {return $age;}
elseif ($month > ($today[4]+1)) {$age--; return $age;} // over by a year
else{ // it's the month the user was born. we need to check the day
if ($day > $today[3]) {$age--; return $age;} // over by a year
else {return $age;}
}
}