【问题标题】:Time zone abbreviations ET, CT, MT, PT时区缩写 ET、CT、MT、PT
【发布时间】:2019-07-24 13:55:29
【问题描述】:

这对吗?

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

【问题讨论】:

  • 有理由不使用$ianatz中提供的值吗?
  • @GlenSolsberry 我想要简短的缩写,例如“ET”,而不是笨重的长“America/New_York”形式。

标签: php datetime time


【解决方案1】:

您可以获得时区缩写。

$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? 的一篇精彩文章

【讨论】:

  • 您也可以建议从$dateTime->format('T') 中删除中间字符,以便为 OP 提供他想要的结果。
  • @Oleg 我在我的问题中特别说过,CST 等 3 个字母的缩写不是我想要的。但是,我真的很欣赏这篇有趣且内容丰富的文章的链接。 :-)
猜你喜欢
  • 1970-01-01
  • 2013-04-02
  • 1970-01-01
  • 2019-04-09
  • 2018-01-23
  • 1970-01-01
  • 2011-08-26
  • 2013-11-26
  • 2015-03-05
相关资源
最近更新 更多