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

DDD
Release: 2024-10-24 12:01:02
Original
951 people have browsed it

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

Calculate Age from Date of Birth in SQL and PHP

Determining the age of a user based on their birth date is a common task in many applications. In this article, we will explore how to achieve this in both SQL and PHP.

SQL Approach

MySQL provides the TIMESTAMPDIFF() function, which allows us to calculate the difference between two timestamps. In our case, we can use this function to calculate the age in years between a user's birth date and the current date. The following query demonstrates this approach:

<code class="sql">SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age</code>
Copy after login

This query will return the age of the user in years. If a user was born on March 15, 1999, the query will return 14. Similarly, if a user was born on March 15, 2014, the query will return 15.

PHP Approach

PHP provides several options for calculating the age of a user from their birth date. The following code snippet demonstrates two approaches using the DateTime class:

<code class="php">// 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;</code>
Copy after login

Both approaches return the age of the user in years. The date_diff() function can also be used to calculate the difference between two DateTime objects, as shown in the procedural approach.

The above is the detailed content of How to Calculate Age from Date of Birth in SQL and PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template