【问题标题】:What is the Zone Id for GMT in Java 8Java 8 中 GMT 的区域 ID 是什么
【发布时间】:2021-01-03 00:32:43
【问题描述】:

我想以秒为单位来确定系统时区是领先还是落后于远程时区。这里的远程时区值是我从数据库中获取的“GMT”。它可能是“美国/东部”,我将其转换为“美国/纽约”。但是对于 GMT,我得到了错误。

ZoneId.systemDefault().getRules().getOffset(Instant.now()).getTotalSeconds() 
    - ZoneId.of("GMT").getRules().getOffset(Instant.now()).getTotalSeconds()

但它给出了以下错误,

Exception in thread "main" java.time.DateTimeException: Invalid ID for ZoneOffset, invalid format: 
    at java.time.ZoneOffset.of(Unknown Source)
    at java.time.ZoneId.of(Unknown Source)
    at java.time.ZoneId.of(Unknown Source)

如何解决这个错误? 用什么代替 GMT ??

【问题讨论】:

  • GMT 并不是真正的时区。我不知道它是什么好名字,但它是“在英国大约半年观察到的东西”。你能提供更多关于你想要达到的目标的信息吗?
  • @JonSkeet - 我已经更新了问题..请检查。
  • “这里的远程时区值是“GMT”,我从数据库中获取”——这是第一个问题,因为“GMT”不是时区。 UTC 也不是,非常严格来说,但通常被接受为一个。因此,假设这是实际含义,您可能只想将“GMT”转换为“UTC”。但是您应该确定 is 是否是数据库中以“GMT”为值的条目所期望的。如果它们实际上的意思是“英国”,那么您应该改用 Europe/London,但这有很大不同
  • "GMT" 对于ZoneId.of(String) 来说是完全有效的输入。无需转换。这里的问题在其他地方。

标签: java-8 timezone java-time


【解决方案1】:

我是ZoneId.of("UTC")...

这是证据:

public static void main(String[] args) {
    // define the ZoneId
    ZoneId utc = ZoneId.of("UTC");
    // get the current date and time using that zone
    ZonedDateTime utcNow = ZonedDateTime.now(utc);
    // define a formatter that uses O for GMT in the output
    DateTimeFormatter gmtStyleFormatter = DateTimeFormatter
                                            .ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS O");
    // and print the datetime using the default DateTimeFormatter and the one defined above
    System.out.println(utcNow + " == " + utcNow.format(gmtStyleFormatter));
}

输出(不久前):

2020-09-16T08:02:34.717Z[UTC] == 2020-09-16T08:02:34.717 GMT

获取该区域的the total zone offset in seconds

utc.getRules().getOffset(Instant.now()).getTotalSeconds();

将导致0,因为该区域没有偏移量。

【讨论】:

    【解决方案2】:

    使用Etc/UTC

    import java.time.Instant;
    import java.time.ZoneId;
    
    public class Main {
        public static void main(String args[]) {
            System.out.println(ZoneId.of("Etc/UTC").getRules().getOffset(Instant.now()).getTotalSeconds());
        }
    }
    

    输出:

    0
    

    【讨论】:

      【解决方案3】:

      官方的回答是:

      等/格林威治标准时间

      除了名称之外,它与其他答案中建议的 Etc/UTC 相同。

      为了完整起见,有许多相同的别名,其中许多已弃用,而不是全部。您可以在链接中找到它们。

      而且我并不反对 cme​​ts 告诉您更喜欢 UTC。我只是想按要求回答问题。

      对于您的情况,您根本不需要询问。 ZoneId.of("GMT").getRules().getOffset(Instant.now()).getTotalSeconds() 应该总是产生 0,所以不需要减去任何东西。我会插入一条为什么我不这样做的评论,或者减去一个命名良好的常量,其值为 0。

      链接: List of tz database time zones

      【讨论】:

        猜你喜欢
        • 2015-11-15
        • 1970-01-01
        • 2019-05-09
        • 2017-08-31
        • 1970-01-01
        • 2019-11-13
        • 2015-05-28
        • 1970-01-01
        • 2018-10-14
        相关资源
        最近更新 更多