Reputation: 11011
I have the following code below:
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(
this.start.toLocalDateTime(), ZoneOffset.UTC,
ZoneOffset.systemDefault());
The this.start is from a java.sql.Timestamp. I am explicitly converting from UTC here to the system's local offset, will this be smarty enough to take into account daylight savings?
Upvotes: 4
Views: 6699
Reputation: 78935
The accepted answer lacks an example. It also compares a ZonedDateTime
with a LocalDateTime
in the context of DST which does not make sense as a LocalDateTime
lacks a time zone. In the context of DST, the comparison should be between a ZonedDateTime
and an OffsetDateTime
. While a ZonedDateTime
, automatically changes the zone offset for a ZoneId
according to the DST, an OffsetDateTime
is used with a fixed zone offset.
Demo
public class Main {
public static void main(String[] args) {
ZoneId zoneId = ZoneId.of("America/New_York");
// A sample ZonedDateTime during DST
ZonedDateTime zdtDuringDST = ZonedDateTime.of(
LocalDate.of(2024, 5, 20),
LocalTime.MIN,
zoneId
);
// A sample ZonedDateTime outside DST
ZonedDateTime zdtOutsideDST = ZonedDateTime.of(
LocalDate.of(2024, 12, 20),
LocalTime.MIN,
zoneId
);
System.out.println(zdtDuringDST);
System.out.println(zdtOutsideDST);
}
}
Output:
2024-05-20T00:00-04:00[America/New_York]
2024-12-20T00:00-05:00[America/New_York]
As you can see in the results, the ZonedDateTime
automatically set the applicable offsets, -04:00 and -05:00 based on the DST. On the other hand, you use an OffsetDateTime
with a fixed zone offset e.g. the zone offset, +01:00 in the below OffsetDateTime
will remain fixed irrespective of change in date and time:
ZoneOffset zoneOffset = ZoneOffset.ofHoursMinutes(1, 0);
OffsetDateTime.of(
LocalDate.of(2024, 5, 20),
LocalTime.MIN,
zoneOffset
);
Learn more about the modern Date-Time API from Trail: Date Time.
Upvotes: 2
Reputation: 303
ZonedDateTime takes daylight savings into account. That's what differs it from LocalDateTime. Well, that and timezone information.
Upvotes: 5