Reputation: 1897
I have a MySQL database with a date_of_birth field. The data stored in this field is of the format: MM-DD-YYYY. I need to compute age for this field so I must compare and take the difference of CurDate()
.
To do this I have written the following:
select FLOOR((DATE_FORMAT(curdate(), '%m-%d-%Y') - date_of_birth)/10000)
from patients
So I would expect it to be comparing the CurDate()
of MM-DD-YYYY minus DOB of MM-DD-YYYY. However, for my one test case it continues to return a -1. I've got this working fine with MSSQL but it seems MySQL is a bit more picky/less user friendly.
Am I missing something here? Whats the deal, please help!
Thanks
Upvotes: 3
Views: 197
Reputation: 2229
You can use datediff()
SELECT DATEDIFF(CURDATE(),date_of_birth) AS Age
Upvotes: 2
Reputation: 16214
SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(date_of_birth, '%Y') -
(DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(date_of_birth, '00-%m-%d'))
AS age
FROM patients
http://ma.tt/2003/12/calculate-age-in-mysql/
ps: if your date is in another format (but I would advise you to keep it 'native' format YYYY-MM-DD) then
SELECT
DATE_FORMAT(NOW(), '%Y') -
DATE_FORMAT(STR_TO_DATE(date_of_birth, '%m-%d-%Y'), '%Y')
- (DATE_FORMAT(NOW(), '00-%m-%d') <
DATE_FORMAT(STR_TO_DATE(date_of_birth, '%m-%d-%Y'), '00-%m-%d'))
AS age
FROM patients
Upvotes: 4