Home > Backend Development > PHP Tutorial > How to Calculate Age from a Given Birth Date?

How to Calculate Age from a Given Birth Date?

Patricia Arquette
Release: 2024-10-24 11:19:29
Original
443 people have browsed it

How to Calculate Age from a Given Birth Date?

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>
    Copy after login
  • Procedural Approach:

    <code class="php">echo date_diff(date_create('1970-02-01'), date_create('today'))->y;</code>
    Copy after login

Using MySQL (>= 5.0.0)

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

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>
Copy after login

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>
    Copy after login
  • 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>
    Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template