Some employers provide benefits in the form of holiday time off. This example uses a custom TemporalQuery that will determine if a date is a company observed holiday. 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 against a list of observed company holidays returning true if a match, otherwise false.
Setup
public class CompanyHolidayQuery implements TemporalQuery<Boolean> {
static List<MonthDay> COMPANY_HOLIDAYS = Lists.newArrayList(
MonthDay.of(Month.JANUARY, 1), // New Years Day January 1
MonthDay.of(Month.JANUARY, 20), // Martin Luther King, Jr. Day January 20
MonthDay.of(Month.APRIL, 18), // Good Friday April 18
MonthDay.of(Month.MAY, 26), // Memorial Day May 26
MonthDay.of(Month.JULY, 4), // Independence Day July 4**
MonthDay.of(Month.SEPTEMBER, 1), // Labor Day September 1
MonthDay.of(Month.NOVEMBER, 27), // Thanksgiving Day November 27*
MonthDay.of(Month.NOVEMBER, 28), // Day after thanksgiving November 28*
MonthDay.of(Month.DECEMBER, 25), // Christmas December 25***
MonthDay.of(Month.DECEMBER, 26) // Day after xmas December 26***
);
/*
* (non-Javadoc)
* @see java.time.temporal.TemporalQuery#queryFrom(java.time.temporal.TemporalAccessor)
*/
@Override
public Boolean queryFrom(TemporalAccessor date) {
MonthDay currentMonthDay = MonthDay.from(date);
return COMPANY_HOLIDAYS.contains(currentMonthDay);
}
}
Date a holiday
@Test
public void is_date_a_holiday () {
LocalDate date = LocalDate.of(2014, Month.DECEMBER, 25); // XMAS
Boolean isHoliday = date.query(new CompanyHolidayQuery());
assertTrue(isHoliday);
}
Date is not a holiday
@Test
public void is_not_date_a_holiday () {
LocalDate date = LocalDate.of(2014, Month.NOVEMBER, 22);
Boolean isHoliday = date.query(new CompanyHolidayQuery());
assertFalse(isHoliday);
}