这有效(返回0):

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


这将失败:

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


例外情况:

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方法的文档说:


  这将以该单位计算金额。起点和终点作为时间对象提供,并且必须具有兼容的类型。在计算金额之前,该实现会将第二种类型转换为第一种类型的实例。


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

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

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

09-16 07:00