Daylight saving query

Daylight saving time (DST) or summer time (see Terminology) is the practice of advancing clocks during the lighter months so that evenings have more apparent daylight and mornings have less. This example will use a custom TemporalQuery that will determine if a date is during daylight saving time. Implementing the TemporalQuery interface with the queryFrom(TemporalAccessor) method allows for a way to extract information from a temporal object. The queryFrom method compares the passed-in date and will return true if between the second Sunday of March and first Sunday in November.

Setup

public class DaylightSavingQuery implements TemporalQuery<Boolean> {

    /* 
     * (non-Javadoc)
     * @see java.time.temporal.TemporalQuery#queryFrom(java.time.temporal.TemporalAccessor)
     */
    @Override
    public Boolean queryFrom(TemporalAccessor temporal) {
    
        LocalDate date = LocalDate.from(temporal);
        
        LocalDate secondSundayInMarch = LocalDate
            .from(date)
            .withMonth(Month.MARCH.getValue())
            .with(TemporalAdjusters.firstInMonth(DayOfWeek.SUNDAY))
            .with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
        
        LocalDate firstSundayInNovember = LocalDate
            .from(date)
            .withMonth(Month.NOVEMBER.getValue())
            .with(TemporalAdjusters.firstDayOfMonth())
            .with(TemporalAdjusters.next(DayOfWeek.SUNDAY));

        if (date.isAfter(secondSundayInMarch) ||
                date.isBefore(firstSundayInNovember)) {
            return true;
        } else {
            return false;
        }
    }
}

Daylight saving time

@Test
public void during_daylight_savings ()  {
    
    LocalDate date = LocalDate.of(2014, Month.JULY, 02); 

    Boolean daylightSavings = date.query(new DaylightSavingQuery());

    assertTrue(daylightSavings);
}

Not daylight saving time

@Test
public void not_during_daylight_savings ()  {
    
    LocalDate date = LocalDate.of(2014, Month.DECEMBER, 02); 

    Boolean daylightSavings = date.query(new DaylightSavingQuery());

    assertTrue(daylightSavings);
}