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
}
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)
The second way, d2
, works as expected.
What is the reason for this difference?