【问题标题】:Java Clock class does not give me the current time [duplicate]Java时钟类没有给我当前时间[重复]
【发布时间】:2019-10-25 13:14:29
【问题描述】:

我尝试使用 Clock 类来获取当前时间。

public class TestClock {
  public static void main(String[] args) {
    Clock c = Clock.systemDefaultZone();
    System.out.println(c.instant());
  }
}

但问题是它没有给我当前时间, 但它给出了:

(当前时间 - 3 小时)

所以我决定更加精确,并在程序中指定我居住的城市。(贝鲁特)

public class TestClock {
  public static void main(String[] args) {
    ZoneId zone = ZoneId.of("Asia/Beirut");
    Clock c = Clock.system(zone);
    System.out.println(c.instant());
  }
}

另外,它给了我:

(当前时间 - 3 小时)。

那么问题出在哪里?

注意:在黎巴嫩-贝鲁特时间 +3 格林威治,此信息与我的问题有关系吗?

【问题讨论】:

  • 瞬间没有时区。
  • 使用ZonedDateTime.now()Instant 没有时区,或者它在 UTC 时区,这取决于你如何看待它。
  • 是的,你是对的,但我还有一个问题:为什么我们可以将 zone 作为参数传递给时钟对象,而时钟类中没有提供时区时间的方法?

标签: java time clock


【解决方案1】:

就像@Erwin Bolwidt 指出的那样,请使用ZonedDateTime 并通过该区域。

public class TestClock {
    public static void main(String[] args) {
        ZoneId zone = ZoneId.of("Asia/Beirut");
        ZonedDateTime zdt = ZonedDateTime.now(zone);
        System.out.println(zdt);
    }
}

结果:

2019-06-11T10:07:20.447+03:00[Asia/Beirut]

【讨论】:

猜你喜欢
  • 2015-10-23
  • 2016-03-03
  • 2019-12-20
  • 2021-03-14
  • 2017-04-02
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多