In the java.time framework of Java 8 and later, the Duration
class says:
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.
Yet when I call the get
method and pass ChronoUnit.DAYS
, an exception is thrown.
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
Am I misunderstanding something, or misusing the classes?
A time-based amount of time, such as '34.5 seconds'. 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.
2. Period Class. The Period class uses the units year, month and day to represent a period of time.
Duration instances are immutable, and are therefore replaced rather than modified, similar to BigDecimal . Duration's can be created using the constructor, or one of the static construction methods such as seconds(double) or minutes(double) .
Documentation for get
on the Duration class.
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.
However, the Duration
class has a method called 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.
The get(TemporalUnit)
method is unfortunately confusing and not intended for most users. To understand why, see this answer.
Java SE 9 will include a much richer set of access methods for Duration
. For now, you can use toDays()
to get the total number of days.
The Javadoc is not exactly wrong, but maybe not perfectly helpful. The class does have some support for days of 24 hours in the toDays()
, ofDays(), plusDays()
etc. It is just that the get(TemporalUnit)
method is very misleadingly named (should be internalGet(TemporalUnit)
or some such name).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With