Home > Software design >  Why does converting an instant to epoch milli and using these epoch millis for a new instant not lea
Why does converting an instant to epoch milli and using these epoch millis for a new instant not lea

Time:12-06

I was trying to save and restore timestamps in a database and stumbled upon this: Why does the second line not return 0?

Instant now = Instant.now();
System.out.println(now.compareTo(Instant.ofEpochMilli(now.toEpochMilli())));

I was expecting to get an instant that would represent the same moment in UTC, but when comparing the two instants as strings, it can be seen that some digits are cut off. What would be the proper way to store an instant in a database?

Example output from the above code:

897000

Output varies between runs but seems to be positive always, meaning that now is greater than Instant.ofEpochMilli(now.toEpochMilli()).

CodePudding user response:

Instant may represent an instant in time with greater than millisecond precision.

The Instant.toEpochMilli() has this note:

If this instant has greater than millisecond precision, then the conversion will drop any excess precision information as though the amount in nanoseconds was subject to integer division by one million.

The result of Instant.ofEpochMilli(now.toEpochMilli()) however can never have greater than millisecond precision.

  • Related