Search code examples
java-8duration

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.


Solution

  • 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);