How to Calculate Age Based on Date of Birth in Code
Calculating a user's age from their date of birth is a common programming task. In PHP, there are multiple methods to achieve this:
Using Object-Oriented DateTime Class (PHP >= 5.3.0)
<code class="php">// Instantiate a DateTime object for the birth date $birthDate = new DateTime('1999-03-15'); // Instantiate a DateTime object for the current date $currentDate = new DateTime('now'); // Calculate the difference between the two dates in years $age = $currentDate->diff($birthDate)->y; // Output the age echo $age;</code>
Using Procedural Date Functions (PHP >= 5.3.0)
<code class="php">// Calculate the difference between the dates using date_diff() $age = date_diff(date_create('1999-03-15'), date_create('now'))->y; // Output the age echo $age;</code>
Using MySQL Query (MySQL >= 5.0.0)
If the date of birth is stored in a MySQL database, the following query can be used to calculate the age:
<code class="sql">SELECT TIMESTAMPDIFF(YEAR, '1999-03-15', CURDATE()) AS age;</code>
This query calculates the difference between the specified date and the current date in years and returns it as the age column.
The above is the detailed content of How to Calculate User Age from Date of Birth in Different Programming Approaches (PHP and MySQL)?. For more information, please follow other related articles on the PHP Chinese website!