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:
$originalDateTime = new DateTime('2022-01-01 12:00:00', new DateTimeZone('Original/Timezone'));
$targetTimeZone = new DateTimeZone('Target/Timezone');
$originalDateTime->setTimezone($targetTimeZone);
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.