TimeZone.getTimeZone("PST") 与 TimeZone.getTimeZone("America/Los_Angeles")

TimeZone.getTimeZone("PST") vs TimeZone.getTimeZone("America/Los_Angeles")

我正在使用 Java 8,

在我们的代码的前面,我们使用 sdf.setTimeZone(TimeZone.getTimeZone("PDT")); 转换为美国太平洋地区,但由于 PDT 不是有效的 ZoneId 而失败(没有抛出任何错误但转换为默认时区)。

所以我寻找 setTimeZone(TimeZone.getTimeZone("PST"));,它在 TimeZone.getAvailableIDs() 值中也不可用。

最后我使用 sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));

现在,我们的一位朋友使用 setTimeZone(TimeZone.getTimeZone("PST")); 转换为美国太平洋时区,并且转换正常进行。

问题是,

TimeZone.getTimeZone("PST");TimeZone.getTimeZone("America/Los_Angeles");有什么区别

哪个更好用?

根据 Java 8 Timezone documentationPST 的使用已被弃用,因为同一个缩写经常用于多个时区。 这就是为什么首选使用 America/Los_Angeles

最好使用 "America/Los_Angeles",因为根据 TZ 数据库,这是有效时区。看到这个 LINK.

For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them..

看到这个LINK

您还可以看到 SO post 表明使用 3 个字母的时区 ID 存在问题。

引用 Error Prone's ThreeLetterTimeZoneID check 的文档:

According to the Javadoc of java.util.TimeZone:

For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as “PST”, “CTT”, “AST”) are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, “CST” could be U.S. “Central Standard Time” and “China Standard Time”), and the Java platform can then only recognize one of them.

除了时区之间的歧义外, 返回时区遵守夏令时, 这意味着获得的 TimeZone 可能不是您所期望的。例子 包括:

DateTime.getTimeZone("PST") 遵守夏令时; 但是,标识符暗示它是太平洋标准时间,即 不遵守夏令时。 DateTime.getTimeZone("EST") (以及 "MST""HST")不遵守夏令时。然而, 这与 PST(和其他)不一致,因此您可能认为 将遵守夏令时。

因此:使用完整的 America/Los_Angeles 格式以尽量减少代码中的歧义。

TL;DR 不要使用 PST。使用 America/Los_Angeles。也不要使用 TimeZone class。使用 ZoneId.

  • PST 可能表示皮特凯恩标准时间、太平洋标准时间或菲律宾标准时间。
  • 如果您将 PST 表示为太平洋标准时间,那不是时区,因为使用它作为标准时间的所有地方当前和一年中的大部分时间都使用太平洋夏令时。
  • 虽然过时的 TimeZone class 对 PST 的解释与 America/Los_Angeles 相同,但正如其他人长期以来所说,三个字母的缩写已被弃用。如果 TimeZone 有一天(尽管不太可能)不再识别 PST,它会给你 GMT,这肯定不是你想要的。

java.time

TimeZone class 设计不佳,有时令人困惑,幸运的是早已过时,由 java.time 中的 ZoneId 现代 Java 取代日期和时间 API,5 年前。

帮助您开始使用现代 API:

的简短代码示例
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)
            .withLocale(Locale.US);
    ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
    System.out.println(dateTime.format(formatter));

Friday, April 12, 2019 at 8:14:09 AM Pacific Daylight Time

ZoneId 的一个优点是它不容易让您使用 PST 作为时区:ZoneId.of("PST") 抛出 java.time.zone.ZoneRulesException: Unknown time-zone ID: PST(如果你坚持,但正如我们所说,你不应该)。

链接