Custom Query

Description

We can create a custom query in two ways.

  • implements the TemporalQuery interface
  • Use method reference as a query. The method should take a TemporalAccessor and return an object.

Example


import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;
//from w  w w .  ja  va2  s .c  o  m
public class Main {

  public static void main(String[] args) {
    LocalDate ld1  = LocalDate.of(2013, 12,1);
    Boolean  is = ld1.query(new Monday1Query()); 
    System.out.println(is);

  }
}

class Monday1Query implements TemporalQuery<Boolean> {
  @Override
  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 == 1 && dayOfWeek == DayOfWeek.MONDAY) {
        return Boolean.TRUE;
      }
    }
    return Boolean.FALSE;
  }
}

The code above generates the following result.

Example 2

The following code rewrites the code above with method reference.


import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAccessor;
//ww  w.  j  a  v  a  2 s.  com
public class Main {

  public static void main(String[] args) {
    LocalDate ld1  = LocalDate.of(2013, 12,   1);
    Boolean  is = ld1.query(Main::queryFrom);
    System.out.println(is);
  }
  public static 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 == 1 && dayOfWeek == DayOfWeek.MONDAY) {
        return Boolean.TRUE;
      }
    }
    return Boolean.FALSE;
  }
}

The code above generates the following result.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial