Using the system's time zone settings in PHP

后端 未结 2 959
既然无缘
既然无缘 2021-01-20 23:26

So I have a web app written in PHP that will run on different Ubuntu servers around the world. Some of the servers will be configured to run on local time, some will run on UTC,

相关标签:
2条回答
  • 2021-01-21 00:06

    If you have timezone set you could use: http://php.net/manual/en/function.date-default-timezone-get.php

    Or http://php.net/manual/en/function.timezone-name-from-abbr.php

    0 讨论(0)
  • 2021-01-21 00:12

    With the help that Andrey Knupp gave in his answer, I was able to solve this one.

    echo "Time: " . date("Y-m-d H:i:s") . "<br>\n";
    
    $shortName = exec('date +%Z');
    echo "Short timezone:" . $shortName . "<br>";
    
    $longName = timezone_name_from_abbr($shortName);
    echo "Long timezone:" . $longName . "<br>";
    
    date_default_timezone_set($longName);
    echo "Time: " . date("Y-m-d H:i:s") . "<br>\n";
    

    Gives output:

    Time: 2011-12-23 23:29:45
    Short timezone:MYT
    Long timezone:Asia/Kuala_Lumpur
    Time: 2011-12-24 06:29:45
    

    Update: The short name for the time zones are not unique. For instance, in both America and Australia there is an "EST", leading timezone_name_from_abbr to sometimes pick the one I don't want to... You can ask date how big the offset is, and that can be used to further match the correct time zone:

    $offset = exec('date +%::z');
    $off = explode (":", $offset);
    $offsetSeconds = $off[0][0] . abs($off[0])*3600 + $off[1]*60 + $off[2];
    $longName = @timezone_name_from_abbr($shortName, $offsetSeconds);
    
    0 讨论(0)
提交回复
热议问题