Java Reference
In-Depth Information
Listing 12-20. A CustomQueries Class with a IsFriday13 Method That Can Be Used a Query
// CustomQueries.java
package com.jdojo.datetime;
import java.time.DayOfWeek;
import static java.time.DayOfWeek.FRIDAY;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.DAY_OF_WEEK;
import java.time.temporal.TemporalAccessor;
public class CustomQueries {
public static Boolean isFriday13(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;
}
}
The following snippet of code uses the method reference of the isFriday13() method in the Custom query class
as a query. The code uses the same datetime objects as in the above example and you get the result.
LocalDate ld1 = LocalDate.of(2013, 12, 13);
Boolean isFriday13 = ld1.query(CustomQueries::isFriday13);
System.out.println("Date: " + ld1 + ", isFriday13: " + isFriday13);
LocalDate ld2 = LocalDate.of(2014, 1, 10);
isFriday13 = ld2.query(CustomQueries::isFriday13);
System.out.println("Date: " + ld2 + ", isFriday13: " + isFriday13);
LocalTime lt = LocalTime.of(7, 30, 45);
isFriday13 = lt.query(CustomQueries::isFriday13);
System.out.println("Time: " + lt + ", isFriday13: " + isFriday13);
Date: 2013-12-13, isFriday13: true
Date: 2014-01-10, isFriday13: false
Time: 07:30:45, isFriday13: false
It is typical of the Date-Time API to provide multiple choices to perform the same task. Let's consider a task of
getting the LocalTime from a ZonedDateTime . The program in Listing 12-21 shows five ways of achieving this.
 
Search WWH ::




Custom Search