Home >Database >Mysql Tutorial >How to Accurately Calculate Age from Date of Birth in MySQL?

How to Accurately Calculate Age from Date of Birth in MySQL?

Barbara Streisand
Barbara StreisandOriginal
2024-11-16 08:20:03912browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn