Java 9. Duration parts, truncation and division.

Grzegorz Gajos
2 min readApr 19, 2017

Java 9 is introducing few new methods in Duration class. Before we jump into the details let’s have a quick recap what Duration is. JavaDoc defines it as the time-based amount of time which is immutable and thread-safe.

Duration.ofHours(-7) // PT-7H
Duration.ofHours(7) // PT7H
Duration.ofSeconds(70) // PT1M10S
Duration.ofNanos(300) // PT0.0000003S
Duration.ofMinutes(-63) // PT-1H-3M S
Duration.ofMinutes(-57) // PT-57M

In the comment on the right, you can see what output goes to console. The output is using format PTnHnMnS. If n = 0 then this part is not displayed. We can parse the output from the string as well.

Duration.parse(“PT7H”) // PT7H

It’s not always straightforward:

Duration.parse(“-PT-6H+3M”)

Is it going to work? Yes. It prints PT5H57M. So, seems like it’s able to calculate the time for you.

Duration.parse(“-PT-6H+3M+7M”)

Is it going to work? We can simplify this to the -PT-6H+10M. So the answer is. No, it won’t. This is not calculator expression. Let’s jump now to the fresh methods introduced in Java 9.

Extracting precision parts

Already in Java 8 we were able to type:

Duration.ofMinutes(130).toMinutes() // 130

Now, we have new method, with the Part suffix:

Duration.ofMinutes(130).toMinutesPart() // 10

In other words, it returns clock number of minutes. The source code behind is also quite trivial:

public int toMinutesPart() {
return (int) (toMinutes() % MINUTES_PER_HOUR);
}

The same is available for other precisions like Hours, Days, etc.

Truncate

In Apache Commons we were able to perform something like:

DateUtils.truncate(new Date(), Calendar.DATE)

Now, similar approach applies to the Duration.

Duration.ofMinutes(130) // PT2H10M
Duration.ofMinutes(130).truncatedTo(ChronoUnit.HOURS) // PT2H
Duration.ofMinutes(130).truncatedTo(ChronoUnit.DAYS) // PT0S
Duration.ofHours(23).truncatedTo(ChronoUnit.DAYS) // PT0S
Duration.ofHours(25).truncatedTo(ChronoUnit.DAYS) // PT24H

Divide

Another new method is dividedBy. Here we can check how many full periods we can fit into specific duration.

Duration.ofHours(25).dividedBy(Duration.ofHours(12)) // 2
Duration.ofHours(9).dividedBy(Duration.ofHours(2)) // 4

Internally, this is operating on the big decimal numbers. No problems with the approximation even with big numbers.

Next Java 9 insights coming soon. In mean time you can find out how Java defines “forever”.

--

--

Grzegorz Gajos

Software Engineer, Co-founder of opentangerine.com. Owner of real, brutal, hands-on experience in diverse IT fields since 2009.