In our codebase I've run into this code converting current timestamp into OffsetDateTime
:
public static OffsetDateTime getUTCTime(){
Date date = new Date();
// Convert Date object to UTC OffsetDateTime object
Instant instant = date.toInstant();
return instant.atOffset(ZoneOffset.UTC);
}
I wonder whether it is possible to replace this code with this:
public static OffsetDateTime getUTCTime(){
return OffsetDateTime.now(ZoneOffset.UTC);
}
Will the returned value be equivalent for both snippets?
There is a difference in accuracy.
In your first code snippet you provide new Date() which uses currentTimeMillis(). When converted into an OffsetDateTime, it can only show up to milliseconds.
Example: "2024-02-02T14:09:04.042Z"
Your second code snippet directly uses the OffsetDateTime object, which is nano second accurate.
Example: "2024-02-02T14:09:04.042471300Z"
Maybe there is a requirement to "only" show/persist the millisecond or if persisted as a string the first one would obviously need less space. As Holger notes in a comment, you can simply use OffsetDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.MILLIS)
to get rid of anything smaller than milliseconds.
Apart from that, I can't tell you if one of them is more efficient.