Home > Blockchain >  Changes in Instant.now() between java 11 and java 17 in AWS Ubuntu standard 6.0
Changes in Instant.now() between java 11 and java 17 in AWS Ubuntu standard 6.0

Time:12-14

We are moving to Java 17 (correto17) from Java 11 (correto11). As part of this, we also have to upgrade Ubuntu to standard:6.0 from standard:4.0 in AWS as mentioned here.

We are observing that in Java 11 and Java 17 Instant.now() output is a bit different.

For example,

System.out.println("Instant: "   Instant.now());

is giving output like below

  • Java 11 - Instant: 2022-12-12T18:04:27.267229Z
  • Java 17 - Instant: 2022-12-12T18:04:27.267229114Z

Can someone let me know what is causing this? How can I make the behaviour same in both the cases?

CodePudding user response:

Instant#now() obtains the current instant from the system clock. If the system clock returns a precision of only up to microseconds, the Instant#toString simply truncates the last three zeros from the nine digits. If the system on which you are running Java 17 (correto17) returns a precision of nanoseconds, you can truncate it to the precision of microseconds using Instant#truncatedTo(java.time.temporal.TemporalUnit).

public class Main {
    public static void main(String args[]) {
        Instant instant = Instant.now();
        Instant truncatedToMicros = instant.truncatedTo(ChronoUnit.MICROS);
        System.out.println(truncatedToMicros);
    }
}

Learn more about the modern Date-Time API from Trail: Date Time.

  • Related