How to Calculate Age from Date of Birth using PHP

On 1/08/2018

Hi! Here we will see how to calculate age from date of birth using php. Working with dates is essential in web development and what we are going to see is a small but very useful utility. Applications such as membership driven websites, social platforms, etc., show the age of the users on their profile page, which they calculate from the date-of-birth of the users. Finding age with the birth date is very easy in php.

If you use PHP 5.3+, consider yourself fortunate as it offers a built-in function called date_diff() that simplifies the task.

php calculate age from date of birth

Using Date_diff() Function:

The function date_diff() in php takes two DateTime objects and returns the difference between them.

You can't pass a date string as it is to the function. First you must convert it into a DateTime object using date_create() and then pass them as arguments.

Consider the following example,

$date1 = date_create('2017-7-10');
$date2 = date_create('2017-7-17');
$interval = date_diff($date1, $date2);
echo $interval->format('%a days');

The above code will output '7 days'. It takes two dates as arguments and returns the difference in the number of days.

PHP - Calculate Age from Date of Birth:

We can use similar logic to find age. To calculate the age, all you have to do is to get the difference between the current date (today) and the birth date.

The following PHP function accepts date of birth as parameter and returns the person's age based on that.

PHP Function to Calculate Age (Procedural Way):

function calculateAge($dob)
    $interval = @date_diff(date_create($dob), date_create('today'));
    return $interval->format('You are %y years, %m months, %d days old.');

echo calculateAge('20-5-1993');
// output
// You are 24 years, 7 months, 16 days old.

The function creates 'DateTime' object from 'date of birth' and 'current date' (today) and passes them to the date_diff() function. Then using format() returns the difference in years, months and days.

The snippet employs a procedural approach. The same can be done with object oriented programming (OOP).

Calculating Age (Object Oriented Sytle):

In the OOP approach, you have to use the function diff(). Here is the PHP function to calculate the age using diff() and oop.

function calculateAge($dob)
    $interval = @(date_create($dob)->diff(date_create('today')));
    return $interval->format('%y years, %m months, %d days');

echo 'Age: ' . calculateAge('20-5-1993');
// output
// Age: 24 years, 7 months, 16 days 

As you can see, both methods are simple and have couple lines of code. Use whichever you want.

Read Also:

That explains about calculating age from date of birth in php. It's a handy feature for social networks and other apps. I hope it's useful to you. Please share the post in your social circle if you like it.

No comments:

Post a Comment

Contact Form


Email *

Message *