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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.