Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 468
Guillaume Robbe Avatar asked Apr 06 '18 10:04

Guillaume Robbe


2 Answers

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()).

like image 78
Holger Avatar answered Nov 17 '22 03:11

Holger


Based on Holger answer, my favorite would be:

final long microseconds = TimeUnit.NANOSECONDS.toMicros(twoSeconds.toNanos())
like image 20
Guillaume Robbe Avatar answered Nov 17 '22 01:11

Guillaume Robbe