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?
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.
Instant now() Method in Java This method requires no parameters and it returns the current instant from the system UTC clock.
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.
Instant class is immutable and provides thread safety as compared to the old Date object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With