Java Data Type How to - Check if a date is School Holiday with TemporalQuery








Question

We would like to know how to check if a date is School Holiday with TemporalQuery.

Answer

import java.time.Month;
import java.time.YearMonth;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;
//  www . j  a  v  a2s  . c  o m
public class Main {

  public static void main(String[] args) {

    YearMonth yearMonth = YearMonth.of(2014, 6);
    System.out.println(yearMonth.query(new SchoolHolidayQuery())); // false
    System.out.println(YearMonth.of(2014, Month.JULY).query(
        new SchoolHolidayQuery())); // true
    System.out.println(YearMonth.of(2014, 8).query(new SchoolHolidayQuery())); // true

  }
}

class SchoolHolidayQuery implements TemporalQuery<Boolean> {
  @Override
  public Boolean queryFrom(TemporalAccessor date) {
    int month = date.get(ChronoField.MONTH_OF_YEAR);
    if (month == Month.JULY.getValue() || month == Month.AUGUST.getValue()) {
      return true;
    }
    return false;
  }
}

The code above generates the following result.