Home > Database > Mysql Tutorial > body text

How to Calculate a Customer's Age from their Date of Birth in MySQL?

Linda Hamilton
Release: 2024-11-16 09:02:03
Original
978 people have browsed it

How to Calculate a Customer's Age from their Date of Birth in MySQL?

Getting Age from Date of Birth in MySQL

To calculate the age of a customer based on their date of birth, it is necessary to subtract the date of birth from the current date. However, the provided expression DATEDIFF(year, customer.dob, "2010-01-01"); is incorrect as it uses a fixed date rather than the current date.

The following formula accurately calculates the age in MySQL:

SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(dob, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(dob, '00-%m-%d')) AS age
Copy after login

This formula subtracts the year of birth from the current year to calculate the age. It also checks if the customer's birthday has not yet passed in the current year by comparing the date formats '00-%m-%d' for both the current date and the date of birth. If the customer's birthday has not yet passed, the age is decremented by one.

The above is the detailed content of How to Calculate a Customer's Age from their 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