Home > Database > Mysql Tutorial > How Can I Calculate Age from a Date of Birth Stored as a String in MySQL?

How Can I Calculate Age from a Date of Birth Stored as a String in MySQL?

Patricia Arquette
Release: 2025-01-16 11:38:58
Original
276 people have browsed it

How Can I Calculate Age from a Date of Birth Stored as a String in MySQL?

Calculate age in MySQL (InnoDB)

If someone's date of birth is stored as a string as 'dd-mm-yyyy', subtracting it from the current date using the DATE() or CURDATE() function will return 'YYYY-MM-DD' format results.

To extract the age from this result, you can use the TIMESTAMPDIFF() function with YEAR units:

<code class="language-sql">SELECT TIMESTAMPDIFF(YEAR, DATE('1970-02-01'), CURDATE()) AS age;</code>
Copy after login

In this example, '1970-02-01' represents the person's date of birth. The resulting age will be the number of complete years that have passed since their birth date.

Demo

<code class="language-sql">SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', '2023-05-01') AS age;</code>
Copy after login

Output:

<code>age
53</code>
Copy after login

This demonstrates how to use TIMESTAMPDIFF() to calculate age based on a stored date of birth and the current date.

The above is the detailed content of How Can I Calculate Age from a Date of Birth Stored as a String 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