How can the DateTime::diff function be utilized in PHP to achieve the desired outcome?

To calculate the difference between two DateTime objects in PHP, you can use the DateTime::diff function. This function returns a DateInterval object representing the difference between two DateTime objects. You can then access the interval properties like days, months, years, etc., to get the desired outcome.

$date1 = new DateTime('2022-01-01');
$date2 = new DateTime('2022-01-10');

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

echo $interval->format('%R%a days');