Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 221
tuk Avatar asked Feb 11 '26 08:02

tuk


2 Answers

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.

like image 58
Arvind Kumar Avinash Avatar answered Feb 15 '26 11:02

Arvind Kumar Avinash


Yes, and what we need to notice is that when we use MacOS, the time API will just works as 6 digs precision, but when we use Linux(such as Ubuntu), it will be 9 digs : )

like image 29
Rico Tea Avatar answered Feb 15 '26 12:02

Rico Tea