Java Reference
In-Depth Information
// Query a LocalDate
LocalDate ld = LocalDate.now();
TemporalUnit precision = ld.query(precisionQuery);
LocalDate queryDate = ld.query(localDateQuery);
System.out.println("Precision of LocalDate: " + precision);
System.out.println("LocalDate of LocalDate: " + queryDate);
// Query a LocalTime
LocalTime lt = LocalTime.now();
precision = lt.query(precisionQuery);
queryDate = lt.query(localDateQuery);
System.out.println("Precision of LocalTime: " + precision);
System.out.println("LocalDate of LocalTime: " + queryDate);
// Query a ZonedDateTime
ZonedDateTime zdt = ZonedDateTime.now();
precision = zdt.query(precisionQuery);
queryDate = zdt.query(localDateQuery);
System.out.println("Precision of ZonedDateTime: " + precision);
System.out.println("LocalDate of ZonedDateTime: " + queryDate);
}
}
Precision of LocalDate: Days
LocalDate of LocalDate: 2014-01-11
Precision of LocalTime: Nanos
LocalDate of LocalTime: null
Precision of ZonedDateTime: Nanos
LocalDate of ZonedDateTime: 2014-01-11
Creating and using a custom query is easy. You can create a custom query in two ways.
TemporalQuery interface and use instances of the
Create a class that implements the
class as a query.
TemporalAccessor and
return an object. The return type of the method defines the result type for the query.
Listing 12-19 contains the code for a Friday13Query class. The class implements the TemporalQuery interface.
The queryFrom() method is part of the interface implementation. The 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. The class defines a constant
IS_FRIDAY_13 that can be used as a query.
Use any method reference as a query. The method should take a
Listing 12-19. A Class Implementing the TemporalQuery Interface
// Friday13Query.java
package com.jdojo.datetime;
import java.time.DayOfWeek;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;
 
Search WWH ::




Custom Search