Java Reference
In-Depth Information
Querying Datetime Objects
All datetime classes support queries. A query is a request for information. Note that you can obtain the components
of a datetime object, for example, the year from a LocalDate , using the get(TemporalField field) method of the
datetime object. Use a query to request information that is not available as components. For example, you can query a
LocalDate whether it is a Friday 13. The result of a query can be of any type.
An instance of the TemporalQuery<R> interface represents a query. All datetime classes contain a query()
method, which takes a TemporalQuery as a parameter and returns a result.
TemporalQueries is a utility class that contains several predefined queries as its static methods, as shown
in Table 12-4 . If a datetime object does not have the information sought in the query, the query returns null. For
example, the query for a LocalDate from a LocalTime object returns null . Chronology is an interface that is used to
identify and manipulate dates in a calendar system.
Table 12-4. List of Utility Methods in the TemporalQueries Class
Method
Return Type
Description
chronology()
TemporalQuery<Chronology>
A query to get the chronology.
localDate()
TemporalQuery<LocalDate>
A query to get the LocalDate .
localTime()
TemporalQuery<LocalTime>
A query to get the LocalTime .
offset()
TemporalQuery<ZoneOffset>
A query to get the ZoneOffset .
precision()
TemporalQuery<TemporalUnit> A query to get the smallest supported unit.
zone()
TemporalQuery<ZoneId>
A query to get the ZoneId . If the ZoneId is not available it queries
for ZoneOffset . It returns null if both are not available, for
example, a LocalDate has neither.
zoneId()
TemporalQuery<ZoneId>
A query to get the ZoneId . If ZoneId is not available, it returns null .
The program in Listing 12-18 shows how to use predefined queries. It uses queries to get the precision and
LocalDate from a LocalDate , a LocalTime , and a ZonedDateTime .
Listing 12-18. Querying Datetime Objects
// QueryTest.java
package com.jdojo.datetime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalQueries;
import java.time.temporal.TemporalQuery;
import java.time.temporal.TemporalUnit;
public class QueryTest {
public static void main(String[] args) {
// Get references of the precision and local date queries
TemporalQuery<TemporalUnit> precisionQuery = TemporalQueries.precision();
TemporalQuery<LocalDate> localDateQuery = TemporalQueries.localDate();
 
 
Search WWH ::




Custom Search