PHP: Calculating a person’s age from their date of birth.

A lot of web applications make the mistake of asking the user to manually enter his or her age. The problem with this approach is that the data becomes redundant if the user doesn’t take the time to update their profile information. i.e. You’re never quite sure how many birthdays the user has had since they first registered with your website.

The best approach is to ask the user to enter his or her date of birth. That way, you can actually calculate what their age is and there is no need for them to update it.

If you’re using PHP versionĀ 5.3.0 or above, then you can make use of the DateTime object:

<?php
//An example date of birth.
$userDob = '1987-04-02';

//Create a DateTime object using the user's date of birth.
$dob = new DateTime($userDob);

//We need to compare the user's date of birth with today's date.
$now = new DateTime();

//Calculate the time difference between the two dates.
$difference = $now->diff($dob);

//Get the difference in years, as we are looking for the user's age.
$age = $difference->y;

//Print it out.
echo $age;

In the code snippet above, you can see that calculating a person’s date of birth with the DateTime object is pretty simple and straight-forward. No need for overly-complex functions!

If you are using a PHP version that is lower than 5.3.0, then you will need to do something like this:

<?php

//Get the current UNIX timestamp.
$now = time();

//Get the timestamp of the person's date of birth.
$dob = strtotime('1987-04-02');

//Calculate the difference between the two timestamps.
$difference = $now - $dob;

//There are 31556926 seconds in a year.
$age = floor($difference / 31556926);

//Print it out.
echo $age;

As you can see, you have to do a lot of the Math yourself.

If you’re looking for a function to use, you can try this:

<?php

function getAge($year, $month, $day){
    $date = "$year-$month-$day";
    if(version_compare(PHP_VERSION, '5.3.0') >= 0){
        $dob = new DateTime($date);
        $now = new DateTime();
        return $now->diff($dob)->y;
    }
    $difference = time() - strtotime($date);
    return floor($difference / 31556926);
}

echo getAge('1987', '12', '02');

Hopefully, you found this tutorial helpful!