Convert date string to UTC time with PHP

后端 未结 2 540
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-24 08:28

I have the following date string

$date=\"Sat Apr 30 2011 18:47:47 GMT+0900 (Tokyo)\"

I want to convert it to UTC time

$timesta         


        
相关标签:
2条回答
  • 2021-01-24 09:19

    The problem is that you code does not automatically echo UTC. It echos the timestamp in whatever your default timezone is set to. This is done via date_default_timezone_set() at runtime or via the configuration setting date.timezone in your php.ini.

    The modern way would be to use the DateTime and the DateTimeZone classes.

    $d = new DateTime('Sat Apr 30 2011 18:47:47 GMT+0900 (Tokyo)');
    print_r($d);
    $d->setTimezone(new DateTimeZone('UTC'));
    print_r($d);
    

    prints

    DateTime Object
    (
        [date] => 2011-04-30 18:47:47
        [timezone_type] => 1
        [timezone] => +09:00
    )
    DateTime Object
    (
        [date] => 2011-04-30 09:47:47
        [timezone_type] => 3
        [timezone] => UTC
    )
    
    0 讨论(0)
  • 2021-01-24 09:19

    You should use gmdate() instead of date() (or you could check the DateTime and DateTimeZone classes in PHP 5.2 / 5.3)

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