Java › Java Date & Time API (java.time)
How would you correctly handle daylight saving time (DST) transitions when performing date-time arithmetic with ZonedDateTime, and what specific pitfalls exist around the 'spring forward' and 'fall back' transitions?
AdvancedAnswer
ZonedDateTime is DST-aware, automatically adjusting its underlying offset when arithmetic operations (like plusHours() or plusDays()) cross a DST transition boundary -- the 'spring forward' transition (clocks skip an hour) means a LOCAL time within that skipped hour genuinely doesn't exist for that specific date (like 2:30 AM on a spring-forward day in a zone that skips from 2:00 to 3:00), which ZonedDateTime resolves by shifting the invalid local time forward by the transition's gap; the 'fall back' transition (clocks repeat an hour) creates a genuinely AMBIGUOUS local time occurring twice, which ZonedDateTime resolves by default to the EARLIER of the two occurrences unless explicitly told otherwise via withEarlierOffsetAtOverlap()/withLaterOffsetAtOverlap() -- these DST-crossing behaviors are subtle and important to understand explicitly rather than assuming naive, fixed-duration arithmetic always behaves as expected.
ZoneId nyZone = ZoneId.of("America/New_York");
// Suppose DST 'springs forward' from 2:00 AM to 3:00 AM on this specific date
ZonedDateTime beforeTransition = ZonedDateTime.of(2024, 3, 10, 1, 30, 0, 0, nyZone);
ZonedDateTime afterAddingHour = beforeTransition.plusHours(1);
// Result correctly accounts for the DST gap -- the LOCAL time jumps by more than a naive 1-hour addition would suggest
System.out.println(afterAddingHour); // reflects the actual wall-clock time after the DST transitionReal-world example A scheduling system computing 'exactly 24 hours from now' for a recurring appointment uses ZonedDateTime.plusDays(1) (which correctly preserves the same local wall-clock time despite any DST transition occurring in between) rather than Instant.plus(Duration.ofHours(24)) (which would produce a DIFFERENT local wall-clock time if a DST transition occurred during that 24-hour span), a critical distinction for correctly modeling recurring local-time-based events.