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>
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>
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!