Java 8 Instant.now() with nanosecond resolution?

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.

Leave a Comment