Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instant vs LocalDateTime - When to prefer one over the other

Tags:

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?

like image 804
galbarm Avatar asked Feb 07 '16 07:02

galbarm


People also ask

Should I use LocalDateTime or Instant?

Instant and LocalDateTime are two entirely different animals: One represents a moment, the other does not. Instant represents a moment, a specific point in the timeline. LocalDateTime represents a date and a time-of-day. But lacking a time zone or offset-from-UTC, this class cannot represent a moment.

What is the difference between date and Instant?

Date, which despite its name, is actually a timestamp. It only stores the number of milliseconds elapsed since the Unix epoch. The new API has many different time representations, each suitable for different use cases: Instant – represents a point in time (timestamp)

Which method of LocalDateTime can be used to get the current date and time?

now() now() method of a LocalDateTime class used to obtain the current date-time from the system clock in the default time-zone. This method will return LocalDateTime based on system clock with default time-zone to obtain the current date-time.

Is Java Instant always UTC?

Instant objects are by default in UTC time zone. Printing the value of timestamp gives us 2016-11-29T14:23:25.551Z . 'Z' here denotes the UTC+00:00 time zone.


1 Answers

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.

like image 142
assylias Avatar answered Sep 19 '22 15:09

assylias