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

查看:19
本文介绍了具有纳秒分辨率的 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天全站免登陆