Date Difference in MySQL to calculate age

2020-02-10 07:04发布

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.

7条回答
一夜七次
2楼-- · 2020-02-10 07:26

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;
查看更多
在下西门庆
3楼-- · 2020-02-10 07:26

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

查看更多
ゆ 、 Hurt°
4楼-- · 2020-02-10 07:33

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;
查看更多
ゆ 、 Hurt°
5楼-- · 2020-02-10 07:42

You mean like this?

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

(Source)

查看更多
你好瞎i
6楼-- · 2020-02-10 07:43
select truncate(datediff(curdate(),dob)/365.25,0) from table;
查看更多
倾城 Initia
7楼-- · 2020-02-10 07:44

Try this

SELECT DATEDIFF(CURDATE(), '2014-02-14');
查看更多
登录 后发表回答