Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of java.util.Date to OffsetDateTime

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?

like image 896
Sergey Tsypanov Avatar asked Oct 14 '25 03:10

Sergey Tsypanov


1 Answers

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.

like image 71
Julius278 Avatar answered Oct 19 '25 14:10

Julius278



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!