Considering the exemple :
final Duration twoSeconds = Duration.ofSeconds(2);
// final long microseconds = twoSeconds.get(ChronoUnit.MICROS); throws UnsupportedTemporalTypeException: Unsupported unit: Micros
final long microseconds = twoSeconds.toNanos() / 1000L;
System.out.println(microseconds);
I wonder if there is a nicer way to get a Duration in microseconds than converting manually from nanoseconds.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With