java – Why can’t I get a duration in minutes or hours in Java.time?

“Why was it implemented this way?”

Other answers deal with methods toXxx() which allow you to query hours / minutes. I will try to address why.

The interface TemporalAmount and the method get(TemporalUnit) they were added quite late in the process. Personally I wasn’t entirely convinced that we had enough evidence of the right way to work the project in that area, but that it was slightly skewed to add TemporalAmount. I believe by doing so we have slightly confused the API.

In hindsight, I believe that TemporalAmount contains the right methods, but I believe that get(TemporalUnit) it should have had a different method name. The reason is that get(TemporalUnit) it’s essentially a framework-level method – it’s not designed for day-to-day use. Unfortunately the name of the method get does not imply this, causing bugs like calling get(ChronoUnit.MINUTES) on Duration.

So, the way you think about get(TemporalUnit) is to imagine a low-level framework by visualizing the amount as Map where is it Duration it’s a Map size two with keys SECONDS And NANOS.

Likewise, Period appears by low-level frameworks as a Map size three – DAYS, MONTHS And YEARS (which fortunately has less chance of errors).

Overall, the best advice for application code is to ignore the method get(TemporalUnit). Use instead getSeconds(), getNano(), toHours() And toMinutes().

Finally, a way to get “hh: mm: ss” from a Duration is to do:

LocalTime.MIDNIGHT.plus(duration).format(DateTimeFormatter.ofPattern("HH:mm:ss"))

It’s not pretty at all, but it works for less than a day.

New methods to…Part in Java 9

JDK-8142936 problem now implemented in Java 9, adding the following methods to access each part of a Duration.

  • toDaysPart
  • toHoursPart
  • toMinutesPart
  • toSecondsPart
  • toMillisPart
  • toNanosPart

Leave a comment