ChronoZonedDateTime withEarlierOffsetAtOverlap() method in Java with Examples


The ChronoZonedDateTime.withEarlierOffsetAtOverlap() method is a part of the Java 8 Date-Time API that returns a copy of the ChronoZonedDateTime with the earlier valid offset during a daylight saving time overlap. This method is useful when you want to handle ambiguous local date-times that occur during a daylight saving time overlap.

Syntax:

public abstract ChronoZonedDateTime<C> withEarlierOffsetAtOverlap()

Here, C represents the chronology of the zoned date-time.

Example 1: Using withEarlierOffsetAtOverlap() method

// create a ZonedDateTime for a daylight saving time overlap
ZonedDateTime zdt = ZonedDateTime.of(2021, 10, 31, 1, 30, 0, 0, ZoneId.of("America/New_York"));

// get the offset before the overlap
ZoneOffset earlierOffset = zdt.withEarlierOffsetAtOverlap().getOffset();

System.out.println("ZonedDateTime: " + zdt);
System.out.println("Earlier Offset: " + earlierOffset);

Output:

ZonedDateTime: 2021-10-31T01:30-04:00[America/New_York]
Earlier Offset: -05:00

In the above example, we create a ZonedDateTime for a daylight saving time overlap on October 31, 2021, at 1:30 AM in the America/New_York time zone. We then use the withEarlierOffsetAtOverlap() method to get the earlier valid offset during the overlap, which is -05:00.

Example 2: Handling ambiguous local date-times

// create a LocalDateTime for a daylight saving time overlap
LocalDateTime ldt = LocalDateTime.of(2021, 10, 31, 1, 30, 0);

// create a ZonedDateTime for the local date-time in the America/New_York time zone
ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/New_York"));

// get the earlier valid offset during the overlap
ZoneOffset earlierOffset = zdt.withEarlierOffsetAtOverlap().getOffset();

System.out.println("LocalDateTime: " + ldt);
System.out.println("ZonedDateTime: " + zdt);
System.out.println("Earlier Offset: " + earlierOffset);

Output:

LocalDateTime: 2021-10-31T01:30
ZonedDateTime: 2021-10-31T01:30-04:00[America/New_York]
Earlier Offset: -05:00

In the above example, we create a LocalDateTime for a daylight saving time overlap on October 31, 2021, at 1:30 AM. We then create a ZonedDateTime for the local date-time in the America/New_York time zone. We use the withEarlierOffsetAtOverlap() method to get the earlier valid offset during the overlap, which is -05:00. This method helps us handle ambiguous local date-times that occur during a daylight saving time overlap.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.