Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does LocalDateTime.ofInstant() requires ZoneId

In Java,

  • If Instant represents a point in time, encoded as date and time in UTC.
  • And LocalDateTime represents a point in time, encoded as date and time in the JVM local timezone.

Why then does LocalDateTime.ofInstant() require a ZoneId as a second argument ?

This makes LocalDateTime not only confusing and potentially incorrect, but also makes it identical to ZonedDateTime; because the timezone of LocalDateTime can be any timezone just like ZonedDateTime.

like image 782
Mike Avatar asked Oct 11 '25 12:10

Mike


2 Answers

And LocalDateTime represents a point in time, encoded as date and time in the JVM local timezone.

No, that's not true. Regardless of the "encoded as" part (which I highly doubt, but which I don't have significant knowledge of to disprove), a LocalDateTime does not represent a point in time. It represents a local date/time, without reference to a specific time zone. Any given LocalDateTime occurs at different points in time in different time zones.

Currently the local date and time in the Europe/London time zone is 2023-01-26T08:50. The same point in time in (say) America/New_York would result in a different LocalDateTime. Whereas in America/New_York, the LocalDateTime of 2023-01-26T08:50 occurs as a different point in time.

For some LocalDateTime / time zone combinations, there may be zero or two corresponding points in time - for example, the LocalDateTime 2022-11-06T01:30 will occur in America/New_York at both 2022-11-06 05:30:00Z and 2022-11-06 06:30:00Z.

Hopefully this is sufficient evidence that a LocalDateTime really isn't a point in time...

like image 142
Jon Skeet Avatar answered Oct 14 '25 02:10

Jon Skeet


A LocalDateTime represents a date and time without time zone information. It is used to represent "local time" (as an example for me, right now the local time is 2023-01-26 09:50). An Instant is always at UTC (example, the time right now is 2023-01-26 08:50 UTC). To transform between an Instant and what the observer considers to be local time, you need to know the ZoneId of the location of the observer (e.g. for me Europe/Amsterdam), otherwise you cannot derive a local time.

And to be clear, a LocalDateTime does not represent a point in time (that is what Instant is for). To expand my example, for me the local time 2023-01-26 09:50 is now past, while for Jon Skeet (in Europe/London), that local time will happen in slightly less than an hour).

like image 34
Mark Rotteveel Avatar answered Oct 14 '25 03:10

Mark Rotteveel