How to Calculate Age from Date of Birth (DOB) in PHP?

How to Calculate Age from Date of Birth (DOB) in PHP?

Hi guys, today we will learn how to get date differences in PHP and how to calculate age from date of birth. We will play with the date of birth using the PHP date and time functions.

Sometimes we need to calculate the user’s age in web applications to make conditions based on the age, so the admin can restrict them according to the date. So for this, we will use PHP date functions in our web applications and calculate the age from the user’s date of birth.

So in this tutorial, I will show simple and easy three methods to calculate the age from date of birth and show it in years, months and days.

Method 1 – Calculate Age Using date()

In this method, we will use date() and strtotime() function and then subtract the current year from the given year. The date() function returns the human-readable date format and strtotime() function return the Unix timestamp in seconds.

When you run the above code, you will get the calculated age based on the date of birth and show it in years. You will see the output below.

Output:
Your age is 26 years.

To get the months and days difference also, create more variables for months and days but change the values of the parameters accordingly.

Output:
Your age is 26 years 0 months 25 days 

Method 2 – Calculate Age Using date_diff()

In this method, we will use date_create() and date_diff() functions. First, we will create today’s date and get the date of birth. Then we will convert these dates in the DateTime object and get the difference between the two dates.

So it will print your current age by changing the value of the $dob variable with your actual date of birth. Or you can make dynamically field to get the user’s age and use it.

Output:
Your age is 26 years.

Let’s suppose you also want to get months and days difference then you can also calculate them and print them. Simply use the $diff->format('%m') and $diff->format('%d') in your code script.

Output:
Your age is 26 years 0 months 25 days 

Method 3 – Calculate Age Using DateTime()

In this method, we will use new DateTime() object and diff() function of it. It is the same as the above method, first convert the dates into objects and then get the difference based on dob using the object diff() function.

Output:
Your age is 26 years.

To get the full years, months, and days difference, use the $diff->m and $diff->d key values. See the following code example.

Output:
Your age is 26 years 0 months 25 days 

You can also make the age calculator or date difference calculator using the above code examples and then get the input of date of birth from users and show the result on submit.

You May Also Like

About the Author: Aman Mehra

Hey! I'm Aman Mehra and I'm a full-stack developer and have 5+ years of experience. I love coding and help to people with this blog.

Leave a Reply

Your email address will not be published.