8

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.

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
chsab420
  • 191
  • 2
  • 3
  • 14
  • Wouldn't "the difference from the current datetime and a DOB" always be that person's age? – Rex M Sep 05 '09 at 14:57

7 Answers7

22

You mean like this?

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

(Source)

Nadia Alramli
  • 111,714
  • 37
  • 173
  • 152
  • Returns Null my date stored is m/d/year, for record which i am working has 1/1/1969 dob. but it returns null :( all the time – chsab420 Sep 05 '09 at 16:42
  • Using TIMESTAMPDIFF is a much better option – Eric Apr 13 '17 at 18:26
  • Missing if today is the birthday SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(NOW(), '2000-05-19')+1), "%Y")+0 AS age from sometable – MMeah May 18 '18 at 19:37
12

You could do this

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

Works everytime.

Sunday Ikpe
  • 924
  • 10
  • 17
1

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;
Martin v. Löwis
  • 124,830
  • 17
  • 198
  • 235
1

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;
Ken Keenan
  • 9,818
  • 5
  • 32
  • 49
0

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

marko
  • 9,029
  • 4
  • 30
  • 46
VISHNU
  • 11
  • 1
0

Try this

SELECT DATEDIFF(CURDATE(), '2014-02-14');
0
select truncate(datediff(curdate(),dob)/365.25,0) from table;
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177