gpt4 book ai didi

2 瞬间之间的 Java 年

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:04:42 24 4
gpt4 key购买 nike

在 Joda 中,我们可以使用

计算 2 个日期时间之间的年份
Years.between(dateTime1, dateTime2);

是否有任何简单的方法可以使用 java.time API 而不是太多逻辑来查找 2 个瞬间之间的年份?

ChronoUnit.YEARS.between(instant1, instant2)

失败:

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Years
at java.time.Instant.until(Instant.java:1157)
at java.time.temporal.ChronoUnit.between(ChronoUnit.java:272)
...

最佳答案

两个瞬间之间的年数被认为是 undefined(显然 - 我对此感到惊讶),但您可以轻松地将瞬间转换为 ZonedDateTime 并获得有用的结果:

Instant now = Instant.now();
Instant ago = Instant.ofEpochSecond(1234567890L);

System.out.println(ChronoUnit.YEARS.between(
ago.atZone(ZoneId.systemDefault()),
now.atZone(ZoneId.systemDefault())));

打印:

8

怀疑您不能直接比较时刻的原因是年份边界的位置取决于时区。这意味着 ZoneId.systemDefault() 可能不是您想要的! ZoneOffset.UTC 将是一个合理的选择,否则如果有一个时区在您的上下文中更有意义(例如,将看到结果的用户的时区),您会想要使用它。

关于2 瞬间之间的 Java 年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47299586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com