Pierre Henry Pierre Henry - 1 month ago 10
Java Question

Why can't I get a duration in minutes or hours in java.time?

Of the Duration class in the new JSR 310 date API (java.time package) available in Java 8, the javadoc 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.


So, why does the following code crash ?

Duration duration = Duration.ofSeconds(3000);
System.out.println(duration.get(ChronoUnit.MINUTES));


This raises an
UnsupportedTemporalTypeException
:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Minutes
at java.time.Duration.get(Duration.java:537)


So what is the recommended way to extract minutes and hours from a duration object ? Do we have to make the calculation ourselves from the number of seconds ? Why was it implemented that way ?

Answer

The documentation says:

This returns a value for each of the two supported units, SECONDS and NANOS. All other units throw an exception.

So, best guess answer -- that's the way they designed it.

You can use some of the other methods to get it in hours:

long hours = duration.toHours();

or minutes:

long minutes = duration.toMinutes();
Comments