How to convert a DateTime object to a string in a different timezone in PHP?

To convert a DateTime object to a string in a different timezone in PHP, you can follow these steps:

  1. Create a DateTime object with the desired date and time.
  2. Use the setTimezone() method to set the desired timezone on the DateTime object.
  3. Use the format() method to convert the DateTime object to a string representation using a specific format.

Here is an example:

$date = new DateTime('2022-01-01 12:00:00', new DateTimeZone('America/New_York')); $date->setTimezone(new DateTimeZone('Europe/Paris')); $strDate = $date->format('Y-m-d H:i:s');

In this example, a DateTime object is created with the date and time '2022-01-01 12:00:00' in the timezone 'America/New_York'. Then, setTimezone() is used to change the timezone to 'Europe/Paris'. Finally, format() is used to convert the DateTime object to a string in the format 'Y-m-d H:i:s', which is stored in the variable $strDate.

You can adjust the format string in format() to fit your desired output format.