与 class 文档相反,持续时间不支持 DAYS

Duration does not support DAYS contrary to class documentation

java.time framework of Java 8 and later, the Durationclass中说:

This class models a quantity or amount of time in terms of seconds and nanoseconds. It can be accessed using other duration-based units, such as minutes and hours. In addition, the DAYS unit can be used and is treated as exactly equal to 24 hours, thus ignoring daylight savings effects.

然而,当我调用 get method and pass ChronoUnit.DAYS 时,抛出异常。

LocalTime start = LocalTime.of ( 0 , 0 , 0 ); // First moment of the day.
LocalTime stop = LocalTime.of ( 2 , 0 , 0 ); // 2 AM.

Duration duration = Duration.between ( start , stop );
long days = duration.get ( ChronoUnit.DAYS );

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Days

我是误会了什么,还是误用了 classes?

持续时间 class 的 get 文档。

Gets the value of the requested unit. This returns a value for each of the two supported units, SECONDS and NANOS. All other units throw an exception.

然而,Duration class 有一个方法叫做 toDays:

Gets the number of days in this duration. This returns the total number of days in the duration by dividing the number of seconds by 86400. This is based on the standard definition of a day as 24 hours.

不幸的是,get(TemporalUnit) 方法令人困惑,不适用于大多数用户。要了解原因,请参阅 this answer

Java SE 9 将为 Duration 包含一组更丰富的访问方法。现在,您可以使用 toDays() 来获取总天数。

Java文档并没有完全错误,但可能不是很有帮助。 class 确实在 toDays()ofDays(), plusDays() 等中支持 24 小时的天数。只是 get(TemporalUnit) 方法的命名非常误导(应该是 internalGet(TemporalUnit) 或类似的名称)。

A.最好换成

LocalTime start = LocalTime.of(0, 0, 0); // First moment of the day.

LocalTime start = LocalTime.MIN; // First moment of the day.

或与

LocalTime start = LocalTime.MIDNIGHT; // First moment of the day.

还有以下

LocalTime stop = LocalTime.of ( 2 , 0 , 0 ); // 2 AM.

可以换成

LocalTime stop = LocalTime.of ( 2 , 0 ); // 2 AM.

B. 您遇到的异常是预期的行为,并且已记录在 Duration:

This returns a value for each of the two supported units, SECONDS and NANOS. All other units throw an exception.

您可以使用 Duration#getUnits 获取支持的单位列表,不幸的是,它已被声明为非静态函数(因此您必须创建任意持续时间才能使用它):

import java.time.Duration;

public class Main {
    public static void main(String[] args) {
        Duration duration = Duration.ofDays(10);// An arbitrary duration
        System.out.println(duration.getUnits());
    }
}

输出:

[Seconds, Nanos]