$date1 = new DateTime('2022-01-01'); $date2 = new DateTime('2022-02-15'); $difference = $date1->diff($date2); echo $difference->format('%R%a days'); // Output: +45 days
$start = new DateTime('2022-01-01 10:00:00'); $end = new DateTime('2022-01-01 12:30:00'); $difference = $start->diff($end); echo $difference->format('%h hours %i minutes'); // Output: 02 hours 30 minutesIn this example, we have two DateTime objects representing the start and end times of a task. We use the diff method to calculate the duration of the task, then format and output the result as hours and minutes. The DateTime diff function is part of the DateTime class in PHP, which is part of the PHP Standard Library.