How can PHP be used to properly calculate and display time durations in a web application?

When calculating and displaying time durations in a web application using PHP, it's important to properly handle time zones and formats to ensure accurate results. One way to achieve this is by using PHP's DateTime class to calculate the time difference between two timestamps and format the duration in a user-friendly way.

// Example code to calculate and display time duration
$startTime = new DateTime('2022-01-01 08:00:00', new DateTimeZone('UTC'));
$endTime = new DateTime('2022-01-01 12:30:00', new DateTimeZone('UTC'));

$duration = $endTime->diff($startTime);
echo $duration->format('%h hours %i minutes'); // Output: 4 hours 30 minutes