使用新的dateTime API获取持续时间 [英] Getting Duration using the new dateTime API
问题描述
I want to get a java.time.Duration
instance representing the duration of 3 years,
and i found 2 ways to do it (see code below).
public static void main(String[] args) {
Duration d1 = Duration.of(3, ChronoUnit.YEARS); //Runtime Exception
Duration d2 = ChronoUnit.YEARS.getDuration().multipliedBy(3);
System.out.println("d2="+d2.toDays()); //OUTPUT: d2=1095
}
第一种方式 d1
,在运行时抛出以下异常:
The first way, d1
, throws the following Exception at runtime:
Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unit must not have an estimated duration
at java.time.Duration.plus(Unknown Source)
at java.time.Duration.of(Unknown Source)
at mod7.vehicalc.Test.main(Test.java:26)
第二种方式, d2
,按预期工作。
The second way, d2
, works as expected.
这个差异的原因是什么?
What is the reason for this difference?
推荐答案
code>持续时间是基于时间的时间。
A Duration
is a time-based amount of time.
A 期间
是基于日期的时间。
A Period
is a date-based amount of time.
鉴于这些年份显然是基于日期的,而不是基于时间的,您需要使用期间
。 (期间
没有复发方面。
Given that years are clearly date-based and not time-based, you need to be using Period
. (There is no "recurrance" aspect to Period
).
Period p = Period.ofYears(3);
ChronoUnit
的预计持续时间方法主要旨在分类单位,即能说一年一般比一个月多。它不是作为数学计算的基础或创建一个更大的持续时间
。特别是,如果您使用期间
,则添加到 LocalDate
或 ZonedDateTime
将导致正确答案。如果您使用持续时间
,那么您可能会收到意外/错误的答案。
The estimated duration method on ChronoUnit
is primarily intended for the purpose of sorting units, ie. being able to say that a year is generally longer than a month. It is not intended to be the basis of mathematical calculations or creating a larger Duration
. In particular, if you use a Period
then addition to a LocalDate
or ZonedDateTime
will result in the correct answer. If you use a Duration
then you will probably get an unexpected/wrong answer.
这篇关于使用新的dateTime API获取持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!