Home >Database >Mysql Tutorial >How to Accurately Calculate Age from Date of Birth in MySQL?
Finding Age from Date of Birth in MySQL
Problem:
Determining the age of a user based on their date of birth, specifically, if the given code using DATEDIFF() fails.
Solution:
The DATEDIFF() function may not accurately calculate age due to potential border cases. Consider using the following query instead:
SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(dob, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(dob, '00-%m-%d')) AS age
This query utilizes DATE_FORMAT() to extract the year from the current date and the date of birth. It also checks if the current day and month are before the user's birthday to account for age adjustments.
The above is the detailed content of How to Accurately Calculate Age from Date of Birth in MySQL?. For more information, please follow other related articles on the PHP Chinese website!