문제

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.

도움이 되었습니까?

해결책

You mean like this?

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

(Source)

다른 팁

You could do this

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

Works everytime.

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;

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;

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

Try this

SELECT DATEDIFF(CURDATE(), '2014-02-14');
select truncate(datediff(curdate(),dob)/365.25,0) from table;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top