Issue
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?
Solution
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.
Answered By - Arvind Kumar Avinash
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.