Guillaume Robbe
Guillaume Robbe

Reputation: 676

Get duration in microseconds

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.

Upvotes: 11

Views: 3530

Answers (2)

Holger
Holger

Reputation: 298579

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);
// Since Java 8
long microseconds8_1 = existingDuration.toNanos() / 1000;
// More idiomatic way
long microseconds8_2 = TimeUnit.NANOSECONDS.toMicros(existingDuration.toNanos());
// Since Java 9
long microseconds9 = existingDuration.dividedBy(ChronoUnit.MICROS.getDuration());
// Since Java 11
long microseconds11 = TimeUnit.MICROSECONDS.convert(existingDuration);    

Upvotes: 13

Guillaume Robbe
Guillaume Robbe

Reputation: 676

Based on Holger answer, my favorite would be:

final long microseconds = TimeUnit.NANOSECONDS.toMicros(twoSeconds.toNanos())

Upvotes: 7

Related Questions