Java TemporalQuery create custom Query

Description

Java TemporalQuery create custom Query

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;

class MyQuery implements TemporalQuery<Boolean> {
  public final static MyQuery Query = new MyQuery();

  @Override/*from w w w  . j  a v  a  2 s  .c o  m*/
  public Boolean queryFrom(TemporalAccessor temporal) {
    if (temporal.isSupported(ChronoField.DAY_OF_MONTH) && 
        temporal.isSupported(ChronoField.DAY_OF_WEEK)) {
      int dayOfMonth = temporal.get(ChronoField.DAY_OF_MONTH);
      int weekDay = temporal.get(ChronoField.DAY_OF_WEEK);
      
      DayOfWeek dayOfWeek = DayOfWeek.of(weekDay);
      
      if (dayOfMonth == 3 && dayOfWeek == DayOfWeek.FRIDAY) {
        return Boolean.TRUE;
      }
    }
    return Boolean.FALSE;
  }
}

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


  }
}



PreviousNext

Related