I know that:
Still in the end IMO both can be taken as type for most application use-cases. As example: Currently I am running a batch job where I need to calculate a next run based on dates and I am struggling to find a pros/cons between these two types (apart from the nanosecond precision advantage of Instant and the time-zone part of LocalDateTime).
Can you name some application examples, where only Instant or LocalDateTime should be used?
Edit: Beware misread documentations for LocalDateTime regarding precision and time-zone
Instant
corresponds to time on the prime meridian (Greenwich).
Whereas LocalDateTime
relative to OS time zone settings, and
cannot represent an instant without additional information such as an offset or time-zone.
You are wrong about LocalDateTime
: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):
A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.
LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.
The difference between the two is that Instant
represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant
objects created at the same moment in two different places of the Earth will have exactly the same value.
One main difference is the Local
part of LocalDateTime
. If you live in Germany and create a LocalDateTime
instance and someone else lives in USA and creates another instance at the very same moment (provided the clocks are properly set) - the value of those objects would actually be different. This does not apply to Instant
, which is calculated independently from time zone.
LocalDateTime
stores date and time without timezone, but it's initial value is timezone dependent. Instant
's is not.
Moreover, LocalDateTime
provides methods for manipulating date components like days, hours, months. An Instant
does not.
apart from the nanosecond precision advantage of Instant and the time-zone part of LocalDateTime
Both classes have the same precision. LocalDateTime
does not store timezone. Read javadocs thoroughly, because you may make a big mistake with such invalid assumptions: Instant and LocalDateTime.
Source: Stackoverflow.com