Home >Database >Mysql Tutorial >How Can I Calculate a Person\'s Age from Their Date of Birth Using PHP and MySQL?
Calculating Age Based on Date of Birth
In a database with user information, it's common to have their birthdates recorded. To enhance the functionality, you may need to convert these birthdates into their corresponding ages (in years).
PHP Solution (>=5.3.0)
Object Oriented:
$from = new DateTime('1970-02-01'); $to = new DateTime('today'); echo $from->diff($to)->y;
Procedural:
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;
MySQL Solution (>=5.0.0)
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age
Implementation in PHP:
$dnn = mysql_fetch_array($dn); $birthDate = $dnn['date']; // Fetch the birth date from the database // Calculate age using the object oriented approach (assuming PHP version is >= 5.3.0) $from = new DateTime($birthDate); $to = new DateTime('today'); $age = $from->diff($to)->y; echo "{$age}"; // Output the calculated age
The above is the detailed content of How Can I Calculate a Person\'s Age from Their Date of Birth Using PHP and MySQL?. For more information, please follow other related articles on the PHP Chinese website!