covert 2 timezones in php

To convert between two timezones in PHP, we can use the DateTime and DateTimeZone classes and the setTimeZone method. Here's an example function:

main.php
function convertTimeZone($dateTimeString, $fromTimeZone, $toTimeZone) {
    $fromTimeZoneObj = new DateTimeZone($fromTimeZone);
    $toTimeZoneObj = new DateTimeZone($toTimeZone);
    $dateTimeObj = new DateTime($dateTimeString, $fromTimeZoneObj);
    $dateTimeObj->setTimeZone($toTimeZoneObj);
    return $dateTimeObj->format('Y-m-d H:i:s');
}
345 chars
8 lines

The function takes three arguments: a string representing the date and time to convert, a string representing the original timezone, and a string representing the target timezone.

Here's an example usage:

main.php
$dateTimeString = '2022-12-31 23:59:59';
$fromTimeZone = 'America/Los_Angeles';
$toTimeZone = 'Asia/Tokyo';
$convertedDateTime = convertTimeZone($dateTimeString, $fromTimeZone, $toTimeZone);
echo $convertedDateTime; // Outputs: 2023-01-01 16:59:59
248 chars
6 lines

In this example, we're converting a date and time in the 'America/Los_Angeles' timezone to the 'Asia/Tokyo' timezone. The output shows the converted date and time in the new timezone.

gistlibby LogSnag