gpt4 book ai didi

java - 转换后的 java.util.Date 的 ChronoUnit.between()

转载 作者:行者123 更新时间:2023-11-29 06:53:31 28 4
gpt4 key购买 nike

这有效(返回 0):

ChronoUnit.SECONDS.between(
LocalDateTime.now(),
LocalDateTime.now());

这失败了:

ChronoUnit.SECONDS.between(
ZonedDateTime.ofInstant(new Date().toInstant(), ZoneId.of("UTC"),
LocalDateTime.now());

除了这个异常(exception):

Exception in thread "main" java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: 2016-10-27T14:05:37.617 of type java.time.LocalDateTime
...
Caused by: java.time.DateTimeException: Unable to obtain ZoneId from TemporalAccessor: 2016-10-27T14:05:37.617 of type java.time.LocalDateTime
at java.time.ZoneId.from(ZoneId.java:466)
at java.time.ZonedDateTime.from(ZonedDateTime.java:553)
... 3 more

有人知道如何在 ChronoUnit.between() 中使用 java.util.Date 吗?

最佳答案

ChronoUnit.between 的文档方法说:

This calculates the amount in terms of this unit. The start and end points are supplied as temporal objects and must be of compatible types. The implementation will convert the second type to be an instance of the first type before the calculating the amount.

它正在尝试将 LocalDateTime 转换为 ZonedDateTimeLocalDateTime 没有区域信息并导致错误。

如果您使用 ZonedDateTime 作为第二个参数,它可以正常工作:

ChronoUnit.SECONDS.between(ZonedDateTime.ofInstant(new Date().toInstant(), ZoneId.of("UTC")), ZonedDateTime.now())

关于java - 转换后的 java.util.Date 的 ChronoUnit.between(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40285404/

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