Calculate the age from date of birth in 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php // Define the date of birth $dateOfBirth = '25-03-1989'; // 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php // 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..!!