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
Release: 2024-11-30 11:04:10
Original
845 people have browsed it

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;
Copy after login

Procedural Approach:

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

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
Copy after login

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!

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