How do I work with time zones and DateTimeImmutable?

Working with time zones in PHP can be done seamlessly using the `DateTimeImmutable` class. This immutable class allows you to work with dates and times while ensuring that the original date/time instance remains unchanged. Here's a simple example of how to use `DateTimeImmutable` to handle time zones:

<?php // Set the timezone $timezone = new DateTimeZone('America/New_York'); // Create a DateTimeImmutable instance $dateTime = new DateTimeImmutable('2023-10-01 12:00:00', $timezone); // Display the date and time in the specified timezone echo $dateTime->format('Y-m-d H:i:s P'); // Output: 2023-10-01 12:00:00 -04:00 // Change the timezone to a different one $newTimezone = new DateTimeZone('Europe/London'); $dateTimeLondon = $dateTime->setTimezone($newTimezone); // Display the date and time in the new timezone echo $dateTimeLondon->format('Y-m-d H:i:s P'); // Output: 2023-10-01 17:00:00 +01:00 ?>

PHP DateTimeImmutable Time Zones Date Handling