How to calculate the age of a person based on their birthdate using DateTime in PHP?

To calculate the age of a person based on their birthdate using DateTime in PHP, you can follow these steps:

  1. Get the current date using the DateTime class:
$currentDate = new DateTime();
  1. Convert the birthdate string into a DateTime object:
$birthdate = new DateTime('1990-05-20');
  1. Calculate the difference between the current date and the birthdate:
$age = $birthdate->diff($currentDate)->y;
  1. Echo the calculated age:
echo "The person's age is " . $age . " years.";

Putting it all together, here's the complete code:

$currentDate = new DateTime(); $birthdate = new DateTime('1990-05-20'); $age = $birthdate->diff($currentDate)->y; echo "The person's age is " . $age . " years.";

This will output: "The person's age is 31 years."