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

后端 未结 9 2065
死守一世寂寞
死守一世寂寞 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.

提交回复
热议问题