What are the best practices for accurately calculating date differences in PHP, considering months and years?

When calculating date differences in PHP, especially when considering months and years, it's important to account for differences in the number of days each month has and leap years. One approach is to use PHP's built-in DateTime class to accurately calculate the difference between two dates, taking into consideration months and years.

$date1 = new DateTime('2022-01-15');
$date2 = new DateTime('2023-03-20');

$interval = $date1->diff($date2);

echo $interval->y . " years, " . $interval->m . " months, " . $interval->d . " days";