Timezone conversion in php

后端 未结 9 1695
我寻月下人不归
我寻月下人不归 2020-11-22 04:19

Can anyone suggest an easy method to convert date and time to different timezones in php?

相关标签:
9条回答
  • 2020-11-22 04:38

    This worked for me and it's pretty clean too!

    function convert_to_user_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
    {
        try {
            $dateTime = new DateTime ($date, new DateTimeZone($serverTimeZone));
            $dateTime->setTimezone(new DateTimeZone($userTimeZone));
            return $dateTime->format($format);
        } catch (Exception $e) {
            return '';
        }
    }
    
    function convert_to_server_date($date, $format = 'n/j/Y g:i A', $userTimeZone = 'America/Los_Angeles', $serverTimeZone = 'UTC')
    {
        try {
            $dateTime = new DateTime ($date, new DateTimeZone($userTimeZone));
            $dateTime->setTimezone(new DateTimeZone($serverTimeZone));
            return $dateTime->format($format);
        } catch (Exception $e) {
            return '';
        }
    }
    
    //example usage
    $serverDate = $userDate = '2014-09-04 22:37:22';
    echo convert_to_user_date($serverDate);
    echo convert_to_server_date($userDate);
    
    0 讨论(0)
  • 2020-11-22 04:38

    I always struggle to remember how exactly setTimezone() method works. Is it adjusting datetime according to timezone? Or does it take a given datetime, drops its timezone, and uses the one you pass? All in all, I'd rather have a more intuitive way to work with timezones.

    I like this one:

    (new AdjustedAccordingToTimeZone(
        new DateTimeFromISO8601String('2018-04-25 15:08:01+03:00'),
        new Novosibirsk()
    ))
        ->value();
    

    It outputs a datetime in ISO8601 format, in Novosibirsk timezone.

    This approach uses meringue library, check out a quick start for more examples.

    0 讨论(0)
  • 2020-11-22 04:43
    <?php
    $time='6:02';
    $dt = new DateTime($time, new DateTimeZone('America/New_York'));
    //echo $dt->format('Y-m-d H:i:s') . PHP_EOL;
    $dt->setTimezone(new DateTimeZone('Asia/Kolkata'));
    echo $dt->format('H:i') . PHP_EOL; 
    ?>
    
    0 讨论(0)
提交回复
热议问题