Java TemporalQuery

TemporalQuery is a standard way of querying the temporal objects (LocalDate, LocalDateTime etc) for making better business decisions. In Java 8, all major date-time classes implement Temporal and TemporalAccessor interfaces so TemporalQuery can be run against all those Java classes.

1. TemporalQuery interface

In the new Java Date API, Temporal interface represents a date, time, or a combination of both. For example, LocalDate, LocalDateTime etc.

TemporalQuery is a functional interface and can, therefore, be used as the assignment target for a lambda expression or method reference. The method queryFrom() takes the Temporal object to query and returns the queried value.

Its implementations define the logic of the query and are responsible for documenting that logic. It may be used by any method on TemporalAccessor to determine the result.

The given is interface definition in Java Standard API.

public interface TemporalQuery<R>
	R queryFrom(TemporalAccessor temporal);

2. TemporalQuery Examples

Let’s see a few examples to understand this interface better.

2.1. Is given time between the business hours?

We can use TemporalQuery to determine if any given time is within a certain range. E.g. time lies between business hours or not.

LocalTime now =;
System.out.println("Currently Working :: " + now.query(WorkingHoursQuery));
private static final TemporalQuery<Boolean> WorkingHoursQuery = temporal -> {
  LocalTime t = LocalTime.from(temporal);
  return t.compareTo(LocalTime.of(9, 0)) >= 0
      && t.compareTo(LocalTime.of(17, 0)) < 0;

2.2. Get Financial Quarter for a Given Date

We can also use TemporalQuery to determine the current financial quarter of the year.

In the below example, the first financial quarter is considered from January to March. Change the method implementation for desired behavior.

LocalDate today =;
System.out.println("Current Financial Quarter :: " + today.query(CurrentQuarterQuery));
private static final TemporalQuery<Integer> CurrentQuarterQuery = temporal -> {
  LocalDate date = LocalDate.from(temporal);
  return (date.getMonthValue() / 3) + 1;

3. Conclusion

In this tutorial, we learned about the TemporalQuery interface and how to use it to query the temporal objects for complex usecases.

Happy Learning !!

Sourcecode Download


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode