首页 > 解决方案 > 时区缩写 ET、CT、MT、PT

问题描述

这个对吗?

是否有一些内置的 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),这样季节的变化不会使标签不正确(例如,对于可以接受任何季节日期的表单输入)。

标签: phpdatetimetime

解决方案


您可以获得时区缩写。

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

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

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

维基百科 UTC

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

另外,我建议阅读 Zach Holman 的一篇很棒的文章UTC 对每个人都足够了吗?


推荐阅读