Java 8 Instant.now()具有纳秒分辨率? [英] Java 8 Instant.now() with nanosecond resolution?

查看:868
本文介绍了Java 8 Instant.now()具有纳秒分辨率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Java 8's java.time.Instant stores in "nanosecond resolution", but using Instant.now() only provides millisecond resolution...

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

结果......

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

我怎样才能得到一个值为'now'但具有纳秒分辨率的Instant?

How can I get an Instant whose value is 'now', but with nanosecond resolution?

推荐答案

虽然默认的Java8时钟不是提供纳秒级分辨率,您可以将其与Java能力相结合,以纳秒级分辨率测量时间差,从而创建一个实际的纳秒级时钟。

While default Java8 clock does not provide nanoseconds resolution, you can combine it with Java ability to measure time differences with nanoseconds resolution, thus creating an actual nanosecond-capable clock.

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

Using it is straightforward: just provide extra parameter to Instant.now(), or call Clock.instant() directly:

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

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

Although this solution might work even if you re-create NanoClock instances every time, it's always better to stick with a stored clock initialized early in your code, then used wherever it's needed.

这篇关于Java 8 Instant.now()具有纳秒分辨率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆