Question:
I’m migrating some signatures fromf(long dur, TimeUnit timeUnit)
to f(Duration duration)
, and would like to implement the former with the latter.Being on Java 8, I can’t find any API to easily convert the
long
+TU
to a Duration
, the only idea that comes to me is to do something ugly like:Answer:
Java 9+
You can use static method
Duration.of(long, TemporalUnit)
.It expects an amount as
long
, and a TemporalUnit
, so you need to convert the TimeUnit into ChronoUnit.toChronoUnit()
was introduced in JDK version 9.Java 8
With Java 8 you can translate
TimeUnit
into ChronoUnit
using ThreeTen library’s utility method Temporals.chronoUnit​(TimeUnit)
If you have better answer, please add a comment about this, thank you!