Get difference in years between two dates in MySQL as an integer

后端 未结 9 2026
死守一世寂寞
死守一世寂寞 2020-11-30 10:59

I am trying to calculate how old is a person in a database.
Let\'s suppose to have this simple table:

student(id, birth_date);

Where

相关标签:
9条回答
  • 2020-11-30 11:22

    I have not enough reputation to add comment to an answer by Rat-a-tat-a-tat Ratatouille to improve his code. Here is the better SQL-query:

    SELECT IFNULL(TIMESTAMPDIFF(YEAR, birthdate, CURDATE()), YEAR(CURDATE()) - YEAR(birthdate)) AS age
    

    This is better because sometimes "birthdate" may contain only year of birth, while day and month is 0. If TIMESTAMPDIFF() returns NULL, we can find rough age by subtracting the current year from the year of birth.

    0 讨论(0)
  • 2020-11-30 11:26

    I'd suggest this:

    DATE_FORMAT(NOW(),"%Y")
       -DATE_FORMAT(BirthDate,'%Y')
       -(
         IF(
          DATE_FORMAT(NOW(),"%m-%d") < DATE_FORMAT(BrthDate,'%m-%d'),
          1,
          0
         )
        ) as Age
    

    This should work with leap-years very well ;-)

    0 讨论(0)
  • 2020-11-30 11:32

    Try:

    SELECT 
      DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(birth_date)), '%Y')+0
      AS age FROM student;
    
    0 讨论(0)
  • 2020-11-30 11:36

    This works, even taking in account leap years!

    select floor((cast(date_format('2016-02-29','%Y%m%d') as int) - cast(date_format('1966-03-01','%Y%m%d') as int)/10000);
    

    Just be sure to keep the floor() as the decimal is not needed

    0 讨论(0)
  • 2020-11-30 11:37

    For anyone who comes across this:

    another way this can be done is:

    SELECT TIMESTAMPDIFF(YEAR, date_of_birth, CURDATE()) AS difference FROM student
    

    For differences in months, replace YEAR with MONTH, and for days replace YEAR with DAY

    Hope that helps!

    0 讨论(0)
  • 2020-11-30 11:41

    Why not use MySQL's FLOOR() function on the output from your second approach? Any fractions will be dropped, giving you the result you want.

    0 讨论(0)
提交回复
热议问题