Guide to 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.

@FunctionalInterface
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 = 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 = LocalDate.now();
 
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

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.