Introduction

You can create a custom query in two ways.

  • Create a class that implements the TemporalQuery interface and use instances of the class as a query.
  • Use any method reference as a query. The method should take a TemporalAccessor and return an object.

The return type of the method defines the result type for the query.

The following code implements the TemporalQuery interface.

queryFrom() method returns true if the datetime object contains a date that falls on Friday 13. Otherwise, it returns false.

The query returns false if the datetime object does not contain a day of month and day of week information, for example a LocalTime object.

Demo

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.DAY_OF_WEEK;
import static java.time.DayOfWeek.FRIDAY;
class Friday13Query implements TemporalQuery<Boolean> {
  public final static Friday13Query IS_FRIDAY_13 = new Friday13Query();

  // Prevent outside code from creating objects of this class
  private Friday13Query() {
  }//from   w  w  w . ja  va 2  s.  com

  @Override
  public Boolean queryFrom(TemporalAccessor temporal) {
    if (temporal.isSupported(DAY_OF_MONTH) && temporal.isSupported(DAY_OF_WEEK)) {
      int dayOfMonth = temporal.get(DAY_OF_MONTH);
      int weekDay = temporal.get(DAY_OF_WEEK);
      DayOfWeek dayOfWeek = DayOfWeek.of(weekDay);
      if (dayOfMonth == 13 && dayOfWeek == FRIDAY) {
        return Boolean.TRUE;
      }
    }
    return Boolean.FALSE;
  }
}

public class Main {
  public static void main(String[] args) {
    LocalDate ld1 = LocalDate.of(2013, 12, 13);
    Boolean isFriday13 = ld1.query(Friday13Query.IS_FRIDAY_13);
    System.out.println("Date: " + ld1 + ", isFriday13: " + isFriday13);

    LocalDate ld2 = LocalDate.of(2014, 1, 10);
    isFriday13 = ld2.query(Friday13Query.IS_FRIDAY_13);
    System.out.println("Date: " + ld2 + ", isFriday13: " + isFriday13);

    LocalTime lt = LocalTime.of(7, 30, 45);
    isFriday13 = lt.query(Friday13Query.IS_FRIDAY_13);
    System.out.println("Time: " + lt + ", isFriday13: " + isFriday13);

  }
}

Result

Related Topic