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

后端 未结 9 2027
死守一世寂寞
死守一世寂寞 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:43

    The accepted answer is almost correct, but can lead to wrong results.

    In fact, / 365 doesn't take into consideration leap years, and can lead to falsy results if you compare a date that has the same day&month than the birthdate.

    In order to be more accurate, you have to divide it by the average days in years for 4 years, aka (365 * 4) + 1 (the leap year every 4 years) => 365.25

    And you will be more accurate :

    select id, floor(datediff(curdate(),birth_date) / 365.25) from student
    

    Tested for one of my project and it's working.

    0 讨论(0)
  • 2020-11-30 11:44
    select id, floor(datediff(curdate(),birth_date) / 365)
    from student
    

    What about flooring the result to be an integer?

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

    You can use this to get integer value.

    select id, CAST(datediff(curdate(),birth_date) / 365 as int)
    from student
    

    If you want to read about CONVERT() and CAST() here is the link.

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