Date time Query
Description
All datetime classes support queries and a query is a request for information.
We can get date time components from a datetime object, for example, we can get
the year from a LocalDate
.
A query requests information that is not available as components. For example, we can query a LocalDate to see if it is Monday. The result of a query can be of any type.
TemporalQuery<R>
interface represents a query.
All datetime classes has a query() method with a TemporalQuery as a parameter.
TemporalQueries
class contains several predefined queries.
If a datetime object does not have the information requested by the query, the query returns null.
Example
The following code shows how to use predefined queries.
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;
/* w w w . j a va 2s .co m*/
public class Main {
public static void main(String[] args) {
TemporalQuery<TemporalUnit> precisionQuery = TemporalQueries.precision();
TemporalQuery<LocalDate> localDateQuery = TemporalQueries.localDate();
// 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);
}
}
The code above generates the following result.