【发布时间】:2021-09-28 22:10:18
【问题描述】:
我正在从服务接收即时信息,以下是案例。
在第一种情况下,说instant = "2021-03-23T04:17:35Z" & 在第二种情况下,
instant = "2021-07-15T05:27:00Z"
然后需要将instant转换为offsetDateTime,就像
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.UTC)
现在我想计算以上 offsetDateTime 和 instant.now 之间的小时差
ChronoUnit.HOURS.between(Instant.parse(offsetDateTime), Instant.now())
结果
案例1:效果很好
案例 2:错误:
DateTimeParseException: Text '2021-07-15T05:27Z' could not be parsed at index 16
找出原因:
在情况 2 中,如果它会通过相同的 2021-07-15T05:27:00Z。它会起作用,但由于instant.atOffset(ZoneOffset.UTC) 内部会调用下面的方法,将删除零,基本上会整理出微小的部分。所以低于 fn 将返回 2021-07-15T05:27Z ,这将导致 DateTimeParseException。
public static OffsetDateTime ofInstant(Instant instant, ZoneId zone) {
Objects.requireNonNull(instant, "instant");
Objects.requireNonNull(zone, "zone");
ZoneRules rules = zone.getRules();
ZoneOffset offset = rules.getOffset(instant);
LocalDateTime ldt = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), instant.getNano(), offset);
return new OffsetDateTime(ldt, offset);
}
我假设一个解决方案是手动附加零,但这可能不是一个好习惯。
【问题讨论】:
-
我投了反对票,因为您的问题不清楚,并且您没有向我们展示失败的代码。 minimal reproducible example 会有很大帮助。
-
Ole V.V.我尝试用我所拥有的任何东西进行解释,我注意到了有问题的根本原因,所以错误是在 Insant 中解析失败,由@Arvind 清除,我只需要花费 offsetDate 时间并直接可以进行转换,没有这样的解析/格式化程序需要转换工作。从今以后,我能够计算出 ChronoUnit.HOURS.between 了。