Extracting Age from Birth Date
In a database with user profiles that include birth dates, calculating age is essential. To convert a birth date into age in years, follow these steps:
Using PHP (>= 5.3.0)
Object-Oriented Approach:
<code class="php">$from = new DateTime('1970-02-01'); $to = new DateTime('today'); echo $from->diff($to)->y;</code>
Procedural Approach:
<code class="php">echo date_diff(date_create('1970-02-01'), date_create('today'))->y;</code>
Using MySQL (>= 5.0.0)
<code class="sql">SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age</code>
Sample PHP Code for Retrieving Age
Given the following PHP code to retrieve a user's birth date from a database:
<code class="php">if(isset($_GET['id'])) { $id = intval($_GET['id']); $dnn = mysql_fetch_array($dn); $dn = mysql_query('select username, email, skype, avatar, ' . 'date, signup_date, gender from users where id="'.$id.'"'); $dnn = mysql_fetch_array($dn); echo "{$dnn['date']}"; }</code>
To calculate the user's age from the retrieved birth date, you can modify the code as follows:
Using Object-Oriented PHP:
<code class="php">// Additional lines to calculate age $birthDate = new DateTime($dnn['date']); $today = new DateTime('today'); $age = $birthDate->diff($today)->y; echo "{$age}";</code>
Using Procedural PHP:
<code class="php">// Additional lines to calculate age $birthDate = date_create($dnn['date']); $today = date_create('today'); $age = date_diff($birthDate, $today)->y; echo "{$age}";</code>
The above is the detailed content of How to Calculate Age from a Given Birth Date?. For more information, please follow other related articles on the PHP Chinese website!