Calculate the age from date of birth in PHP
📅December 16, 2020
🗁PHP
Today we’ll explain to you how to calculate the age from date of birth in PHP. Sometimes we need to calculate the age of the user in web applications. So here, we will show you the easy ways to calculate the age of users in years, months and days using PHP.
Follow the steps to calculate the age.
- Define the date of birth
- Get Today’s date
- Get different between two dates to calculate the current age
Let’s calculate the age using the two different methods.
Method 1
Check the following code to calculate the date of birth.
<!--?php
// Define the date of birth
$dateOfBirth = '25-03-1989';<p-->
// Create a datetime object using date of birth
$dob = new DateTime($dateOfBirth);
// Get today's date
$now = new DateTime();
// Calculate the time difference between the two dates
$diff = $now->diff($dob);
// Get the age in years, months and days
echo "Your current age is ".$diff->y." years ".$diff->m." months ".$diff->d." days";
?>
Method 2
In the second method, we will calculate the age using date(), date_create(), and date_diff() functions in PHP.
<!--?php<p-->
// Define the date of birth
$dateOfBirth = '25-03-1989';
// Get today's date
$today = date("Y-m-d");
// Calculate the time difference between the two dates
$diff = date_diff(date_create($dateOfBirth), date_create($today));
// Get the age in years, months and days
echo "your current age is ".$diff->format('%y')." Years".$diff->format('%m')." months ".$diff->format('%d')." days";
?>
Here, we have calculated the age in years, months, and days but you can use it as per your requirements.
That’s it for today.
Thank you for reading. Happy Coding..!!