Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Instant.now() with nanosecond resolution?

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?

like image 880
user1615355 Avatar asked Dec 19 '13 18:12

user1615355


People also ask

How accurate is instant now?

Instant may model the time to nanosecond precision, but as for the actual resolution, it depends on the underlying OS implementation. On Windows, for example, the resolution is pretty low, on the order of 10 ms. Compare this with System.

What does instant NOW () return in Java?

Instant now() Method in Java This method requires no parameters and it returns the current instant from the system UTC clock.

Is Java Instant always UTC?

Instant objects are by default in UTC time zone. Printing the value of timestamp gives us 2016-11-29T14:23:25.551Z . 'Z' here denotes the UTC+00:00 time zone.

Is Instant immutable?

Instant class is immutable and provides thread safety as compared to the old Date object.


1 Answers

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.

like image 97
logtwo Avatar answered Sep 20 '22 17:09

logtwo