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

How to Calculate Age from Date of Birth in PHP and MySQL?

Susan Sarandon
Susan SarandonOriginal
2024-11-30 11:04:10847browse

How to Calculate Age from Date of Birth in PHP and MySQL?

How to Calculate Age Based on Date of Birth

Background

In a database with a table containing user information, including their birth dates, a common task is to convert these dates into the users' ages. This article presents a solution in PHP and MySQL to accomplish this conversion.

PHP

To calculate the age in PHP, you can use either object-oriented or procedural approaches.

Object-Oriented Approach:

$from = new DateTime('1970-02-01');
$to   = new DateTime('today');
echo $from->diff($to)->y;

Procedural Approach:

echo date_diff(date_create('1970-02-01'), date_create('today'))->y;

MySQL

In MySQL, the TIMESTAMPDIFF() function can be used to calculate the age based on two dates:

SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age

By using these methods, you can efficiently convert user birth dates to their corresponding ages, providing valuable information for various applications.

The above is the detailed content of How to Calculate Age from Date of Birth in PHP and 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