java - Duration 不支持与类文档相反的 DAYS

标签 java duration java-time

java.time Java 8 及更高版本的框架,Duration类说:

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方法并通过 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

我是不是误解了什么,或者滥用了类(class)?

最佳答案

关于 Duration 类的 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 类有一个名为 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.

关于java - Duration 不支持与类文档相反的 DAYS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35165551/

相关文章:

java - java.time 无法解析秒的小数部分吗?

java - 如何在保留先前文本的同时输入 HTML JEditorPane?

java - 推土机映射 JodaTime 属性未按预期工作

Java - 解析日期/期间的优雅方式?

c# - C#中方法的持续时间,时间开始和时间结束

java - IST 映射到 java.time 库中的错误 ZoneId

java - ZonedDateTime 现在函数强制包含第二个值

java - 读取 API 响应的通用代码

Java、Spring、Apache Tiles 错误 : Could not resolve view with name 'index' in servlet with name 'dispatcher'

java - 在 Java 中反序列化人类可读持续时间的最简单方法是什么?