use*_*872 6 java datetime date-difference java-8 java.time.instant
在Joda中,我们可以计算2个Datetime之间的年份
Years.between(dateTime1, dateTime2);
Run Code Online (Sandbox Code Playgroud)
是否有任何简单的方法可以在2个时刻之间找到使用java.timeAPI而没有太多逻辑的年份?
ChronoUnit.YEARS.between(instant1, instant2)
Run Code Online (Sandbox Code Playgroud)
失败:
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)
...
Run Code Online (Sandbox Code Playgroud)
两个瞬间之间的年数被认为是未定义的(显然 - 我对此感到惊讶),但您可以轻松地将瞬间转换为ZonedDateTime并获得有用的结果:
Instant now = Instant.now();
Instant ago = Instant.ofEpochSecond(1234567890L);
System.out.println(ChronoUnit.YEARS.between(
ago.atZone(ZoneId.systemDefault()),
now.atZone(ZoneId.systemDefault())));
Run Code Online (Sandbox Code Playgroud)
打印:
8
Run Code Online (Sandbox Code Playgroud)
我怀疑你不能直接比较时刻的原因是因为年边界的位置取决于时区.这意味着ZoneId.systemDefault()可能不是你想要的!ZoneOffset.UTC将是一个合理的选择,否则,如果在您的上下文中有一个更有意义的时区(例如,将看到结果的用户的时区),您将要使用它.
| 归档时间: |
|
| 查看次数: |
1036 次 |
| 最近记录: |