How can one efficiently handle different time formats and time zones in PHP when calculating working hours?

When handling different time formats and time zones in PHP when calculating working hours, it is essential to standardize all input times to a common time zone before performing any calculations. This can be achieved by using PHP's DateTime class along with DateTimeZone to convert all times to a specific time zone. Once all times are in the same time zone, working hours can be accurately calculated by subtracting the start time from the end time.

// Set the time zone for all calculations
$timezone = new DateTimeZone('America/New_York');

// Convert start and end times to DateTime objects in the specified time zone
$start = new DateTime('2022-01-01 09:00:00', $timezone);
$end = new DateTime('2022-01-01 17:00:00', $timezone);

// Calculate the working hours by subtracting start time from end time
$working_hours = $end->diff($start)->format('%h hours %i minutes');

echo "Working hours: " . $working_hours;