Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duration does not support DAYS contrary to class documentation

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?

like image 733
Basil Bourque Avatar asked Feb 02 '16 23:02

Basil Bourque


People also ask

What does duration mean in coding?

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.

Which of the following class represents duration of time in terms of years months and days?

2. Period Class. The Period class uses the units year, month and day to represent a period of time.

Is Java duration immutable?

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) .


2 Answers

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.

like image 125
kunruh Avatar answered Oct 20 '22 07:10

kunruh


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).

like image 38
JodaStephen Avatar answered Oct 20 '22 09:10

JodaStephen