Get duration in microseconds
I wouldn’t use the java.time
API for such a task, as you can simply use
long microseconds = TimeUnit.SECONDS.toMicros(2);
from the concurrency API which works since Java 5.
However, if you have an already existing Duration
instance or any other reason to insist on using the java.time
API, you can use
Duration existingDuration = Duration.ofSeconds(2);
long microseconds = existingDuration.dividedBy(ChronoUnit.MICROS.getDuration());
Requires Java 9 or newer
For Java 8, there seems to be indeed no nicer way than existingDuration.toNanos() / 1000
or combine the two APIs like TimeUnit.NANOSECONDS.toMicros(existingDuration.toNanos())
.
Based on Holger answer, my favorite would be:
final long microseconds = TimeUnit.NANOSECONDS.toMicros(twoSeconds.toNanos())