What potential pitfalls should be considered when calculating time differences in PHP, especially when crossing midnight?

When calculating time differences in PHP, especially when crossing midnight, it's important to consider the possibility of negative time differences. This can occur when the end time is before the start time, resulting in a negative value. To handle this, you can use the DateTime class in PHP to accurately calculate time differences across midnight.

$start = new DateTime('2022-01-01 23:00:00');
$end = new DateTime('2022-01-02 01:00:00');

if ($end < $start) {
    $end->modify('+1 day');
}

$interval = $start->diff($end);
echo $interval->format('%H:%I:%S');