Date Difference in MySQL to calculate age

人盡茶涼 提交于 2019-11-30 07:31:50

问题


I have a problem regarding the datediff MYSQL function, I can use it and it is simple. But I don't understand how to use it to collect differences within the table field. E.g.

I have a column dob and I want to write a query that will do something like

select dateDiff(current_timeStamp,dob) 
from sometable 'here dob is the table column

I mean I want the difference from the current date time to the table field dob, each query result is the difference, the age of the user.


回答1:


You mean like this?

SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), dob)), "%Y")+0 AS age from sometable

(Source)




回答2:


You could do this

SELECT TIMESTAMPDIFF(YEAR, date_of_birth, NOW()) ASageFROM your_table

Works everytime.




回答3:


If you want, for each user, display the age in years, do

select name,extract(year from (from_days(dateDiff(current_timestamp,dob)))) 
       from sometable;



回答4:


If I understand your comments on the previous answers, the date-of-birth column is not actually a DATE value but a string in the format m/d/y. I strongly recommend you change this; it slows down any date computations you want to do and you risk invalid date values getting entered into the column.

I think this is what you need. It uses the STR_TO_DATE() function and an algorithm for computing the age from the MySQL documentation:

SELECT YEAR(CURDATE()) - YEAR(STR_TO_DATE(dob, '%m/%d/%Y'))
- (RIGHT(CURDATE(), 5) < RIGHT(STR_TO_DATE(dob, '%m/%d/%Y'), 5)) AS age
FROM sometable;



回答5:


I think this should help

SELECT DATE_FORMAT(FROM_DAYS(TO_DAYS(now()) - TO_DAYS(@dateofbirth)), '%Y') + 0;

Note: Give the D.O.B in the correct format, E.g. YYYY-MM-DD'=> '1991-11-11




回答6:


Try this

SELECT DATEDIFF(CURDATE(), '2014-02-14');



回答7:


select truncate(datediff(curdate(),dob)/365.25,0) from table;


来源:https://stackoverflow.com/questions/1383516/date-difference-in-mysql-to-calculate-age

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!