获取以微秒为单位的持续时间

Get duration in microseconds

考虑示例:

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

我想知道是否有比从纳秒手动转换更好的方法来获取以微秒为单位的持续时间。

我不会使用 java.time API 来完成这样的任务,因为您可以简单地使用

long microseconds = TimeUnit.SECONDS.toMicros(2);

来自 concurrency API 自 Java 5.

起有效

但是,如果您有一个已经存在的 Duration 实例或任何其他原因坚持使用 java.time API,您可以使用

Duration existingDuration = Duration.ofSeconds(2);
long microseconds = existingDuration.dividedBy(ChronoUnit.MICROS.getDuration());

需要 Java 9 或更高版本

对于 Java 8,似乎确实没有比 existingDuration.toNanos() / 1000 或将两个 API 组合起来更好的方法,例如 TimeUnit.NANOSECONDS.toMicros(existingDuration.toNanos())

根据 Holger 的回答,我最喜欢的是:

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