Java 8 Instant.now() with nanosecond resolution?

user1615355 picture user1615355 · Dec 19, 2013 · Viewed 44.8k times · Source

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

Result...

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

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

Answer

logtwo picture logtwo · Jul 29, 2016

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

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

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.