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!