时区缩写ET,CT,MT,PT

时间:2019-03-02 21:25:41

标签: php datetime time

这正确吗?

是否有一些内置的PHP方式或我应该使用的库而不是此自定义函数?

/**
 * Supports the 4 Generalized Time Zones shown here: https://www.timeanddate.com/time/zone/usa of the contiguous U.S. (https://en.wikipedia.org/w/index.php?title=Time_in_the_United_States&oldid=885295732#Zones_used_in_the_contiguous_U.S.)
 * @see https://en.wikipedia.org/wiki/Tz_database
 * 
 * @param string $ianatz
 * @return string
 * @throws \Exception
 */
public static function getUsaGeneralizedTimeZoneAbbrev($ianatz) {
    if ($ianatz == 'America/New_York') {
        return 'ET';
    } else if ($ianatz == 'America/Chicago') {
        return 'CT';
    } else if ($ianatz == 'America/Phoenix') {
        return 'MT';
    } else if ($ianatz == 'America/Los_Angeles') {
        return 'PT';
    } else {
        throw new \Exception('Please use one of the 4 supported time zones of the contiguous USA.');
    }
}

注意:我对EDT与EST不感兴趣。我希望使用通用版本(ET),以便季节的更改不会使标签不正确(例如,对于可以接受任何季节的日期的表单输入)。

1 个答案:

答案 0 :(得分:0)

您可以获得时区缩写。

$dateTime = new DateTime(); 
$dateTime->setTimeZone(new DateTimeZone('America/Chicago')); 

$dateTime->format('T'); // CST

但是我建议以没有DST的形式使用UTC。

Wikipedia UTC

  

UTC不会随季节的变化而变化,但是如果时区所在区域遵守夏令时或夏令时,则当地时间或民用时间可能会发生变化。例如,冬季时UTC比美国东海岸的当地时间早5小时,而夏季则比当地时间早4小时。

此外,我建议阅读Zach Holman的精彩文章UTC is enough for everyone right?