Java 8 Instant.now()具有纳秒分辨率?

Java 8的java.time.Instant以“纳秒分辨率”存储,但使用Instant.now()仅提供毫秒分辨率……

Instant instant = Instant.now(); System.out.println(instant); System.out.println(instant.getNano()); 

结果…

 2013-12-19T18:22:39.639Z 639000000 

我怎样才能获得一个“现在”值但具有纳秒分辨率的瞬间?

虽然默认的Java8时钟不提供纳秒分辨率,但您可以将其与Javafunction结合使用,以纳秒分辨率测量时差 ,从而创建一个实际的纳秒级时钟。

 public class NanoClock extends Clock { private final Clock clock; private final long initialNanos; private final Instant initialInstant; public NanoClock() { this(Clock.systemUTC()); } public NanoClock(final Clock clock) { this.clock = clock; initialInstant = clock.instant(); initialNanos = getSystemNanos(); } @Override public ZoneId getZone() { return clock.getZone(); } @Override public Instant instant() { return initialInstant.plusNanos(getSystemNanos() - initialNanos); } @Override public Clock withZone(final ZoneId zone) { return new NanoClock(clock.withZone(zone)); } private long getSystemNanos() { return System.nanoTime(); } } 

使用它很简单:只需为Instant.now()提供额外参数,或直接调用Clock.instant():

  final Clock clock = new NanoClock(); final Instant instant = Instant.now(clock); System.out.println(instant); System.out.println(instant.getNano()); 

虽然每次重新创建NanoClock实例时此解决方案都可能有效,但最好始终在代码中尽早初始化存储时钟,然后在需要的地方使用。

如果你获得甚至毫秒的分辨率,你可以认为自己很幸运。

Instant可以将时间建模为纳秒级精度,但是计算机上跟踪挂钟时间的真实设备通常具有大约10 ms的分辨率,并且几乎可以肯定地准确度相当于100 ms(100 ms将是一个乐观的假设)。

将其与System.nanoTime()进行比较,后者以微秒为单位给出分辨率,但不给出绝对的挂钟时间。 很明显,在工作中已经有了权衡,可以给你那种分辨率,仍然是纳秒的三个数量级。

通过使用Instant-method public static Instant now(Clock clock)使用另一个更精确的java.time.Clock,你只能获得一个“纳秒”的public static Instant now(Clock clock)在你的例子中,默认时钟通常使用System.currentTimeMillis(),它无法显示任何纳秒。

请注意,没有时钟可用纳秒分辨率(实时)。 java.time.Instant的内部纳秒表示工具主要是由于需要映射以纳秒精度给出的数据库时间戳(但通常不精确到纳秒!)。

从2015-12-29更新: Java-9将提供更好的时钟,请参阅我的新post 。

所以我花了一些时间在这里挖掘Javadoc:

http://download.java.net/jdk8/docs/api/java/time/Instant.html

您似乎应该能够执行以下操作:

 Instant inst = Instant.now(); long time = inst.getEpochSecond(); time *= 1000000000l; //convert to nanoseconds time += inst.getNano(); //the nanoseconds returned by inst.getNano() are the nanoseconds past the second so they need to be added to the epoch second 

也就是说 – 其他的回答者说得很好,因为计算机通常没有足够的时间跟踪分辨率,因此很难获得准确的纳秒时间。