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
Release: 2024-11-16 08:20:03
Original
915 people have browsed it

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template