How to Calculate Age From Birthdate in PHP?

To calculate a person's age from their birthdate in PHP, you simply need to get the difference in years between the birthdate and the date today. This can be done in the following way:

$birthdate = new DateTime('1999-05-01');
$today = new DateTime();
$diff = $today->diff($birthdate);
$age = (int) $diff->format('%y');

echo $age; // 22

Please note that the return value of the DateTimeInterface::diff() method is an instance of DateInterval class. When you use the DateInterval::format() method, it returns a string. Therefore, casting the formatted output to an integer is important in this case to ensure the correct type.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.