galbarm
galbarm

Reputation: 2543

Instant vs LocalDateTime - When to prefer one over the other

I need to save and present datetime of events that happened in my server in UTC. I have the option of using Instant.now() or LocalDateTime.now(ZoneOffset.UTC)

When should I prefer one over the other?

Upvotes: 24

Views: 10967

Answers (1)

assylias
assylias

Reputation: 328629

It depends on what you want to do with the data. The two types are conceptually different.

Imagine the event happened at 8am UTC.

Once you have a LocalDateTime, you have lost the time zone information and it could technically be in any time zone - so maybe 8am UTC or 8am EST (= 1pm UTC). It means that you have to "know" that your convention is that that LocalDateTime is in fact a UTC moment.

If you use an Instant, you know exactly what moment in time is being referred to, regardless of time zones, and don't need external "knowledge" or convention. However you don't have time zone information either so you don't know if it is 8am UK time of 9am CET or 3am EST (but these all represent the same moment in time).

Finally, if you need both the moment in time and with which time zone it should be associated, you could use a ZonedDateTime or OffsetDateTime which will have the Instant and the time zone information.

Upvotes: 32

Related Questions