How to convert UTC datetime to another timezone?

前端 未结 3 2028
日久生厌
日久生厌 2020-12-02 20:22

How can i convert a date like this: 2012-07-16 01:00:00 +00 (it\'s in the UTC +00:00 timezone) to UTC +04:00 timezone? Ensuring that d

相关标签:
3条回答
  • 2020-12-02 21:00

    Use DateTime and DateTimeZone.

    $date = new DateTime('2012-07-16 01:00:00 +00');
    $date->setTimezone(new DateTimeZone('Europe/Moscow')); // +04
    
    echo $date->format('Y-m-d H:i:s'); // 2012-07-15 05:00:00 
    
    0 讨论(0)
  • 2020-12-02 21:17

    You can also use GMT time also and convert it to your requirement afterwards

    <?php
    echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
    ?>
    

    GMT refers Greenwich Mean Time which is common all over the world.

    0 讨论(0)
  • 2020-12-02 21:19

    To help with the solution, you need to get the last part of the string (the offset part) and look it up against a simple lookup. you can use a regex or substr() (maybe) to get the offest part. Then, when you have a + or - value, use a maximum of 24 lookups against possible timezones which you can use with PHP's possible timezones - if the offset is the same, who cares what the actual country/location is?

    The use date_default_timezone_set to apply the right one.

    0 讨论(0)
提交回复
热议问题