"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Calculate Accurate Age Difference in Years Between Two Dates in MySQL?

How to Calculate Accurate Age Difference in Years Between Two Dates in MySQL?

Published on 2024-11-15
Browse:424

How to Calculate Accurate Age Difference in Years Between Two Dates in MySQL?

Getting the Age Difference in Years Between Two Dates in MySQL

In MySQL, calculating the age difference between two dates can be challenging, especially if you want it as an integer. Frequently, using DATEDIFF() or dividing by 365 will result in floating-point values or years with possible inaccuracies.

One effective method involves using TIMESTAMPDIFF() with the appropriate date units:

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

This expression calculates the difference in years between the date_of_birth and the current date CURDATE(). By substituting 'YEAR' with 'MONTH' or 'DAY,' you can obtain the difference in months or days, respectively.

For example, if a person was born on June 1, 1970, and the current date is May 15, 2023, the expression will evaluate to 52, accurately representing their current age in years.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3