Home >Database >Mysql Tutorial >How Can I Calculate a Person\'s Age from Their Date of Birth Using PHP and MySQL?

How Can I Calculate a Person\'s Age from Their Date of Birth Using PHP and MySQL?

DDD
DDDOriginal
2024-11-25 10:25:11619browse

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!

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