How to convert a DateTime object to a different time zone and display it in a specific format in PHP?

To convert a DateTime object to a different time zone and display it in a specific format in PHP, you can use the following steps:

  1. Create a DateTime object with the original date and time.
$originalDateTime = new DateTime('2022-01-01 12:00:00', new DateTimeZone('Original/Timezone'));
  1. Set the new time zone by creating a new DateTimeZone object.
$targetTimeZone = new DateTimeZone('Target/Timezone');
  1. Change the time zone of the original DateTime object to the new time zone.
$originalDateTime->setTimezone($targetTimeZone);
  1. Format the DateTime object to display in the desired format using the format() method and store it in a variable.
$formattedDateTime = $originalDateTime->format('Y-m-d H:i:s');

Here's an example of converting a DateTime object from 'America/New_York' time zone to 'Asia/Tokyo' time zone using the format 'Y-m-d H:i:s' (Year-Month-Day Hour:Minute:Second):

$originalDateTime = new DateTime('2022-01-01 12:00:00', new DateTimeZone('America/New_York')); $targetTimeZone = new DateTimeZone('Asia/Tokyo'); $originalDateTime->setTimezone($targetTimeZone); $formattedDateTime = $originalDateTime->format('Y-m-d H:i:s'); echo $formattedDateTime;

Output: 2022-01-02 02:00:00

This will convert the original DateTime object from 'America/New_York' to 'Asia/Tokyo' time zone and display the formatted date and time.