Java 8 – TemporalQuery

TemporalQuery is a standard way of querying the temporal objects 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

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

The implementation defines the logic of the query and is responsible for documenting that logic. It may use any method on TemporalAccessor to determine the result.

The input object must not be altered.

@FunctionalInterface
public interface TemporalQuery<R> 
{
	R queryFrom(TemporalAccessor temporal);
}

2. TemporalQuery Example

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

2.1. A given tome is within 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;
};

Program output:

Currently Working :: false

2.2. Get current financial quarter

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;
};

Program output:

Current Financial Quarter :: 2

Drop me your questions related to using TemporalQuery with dates in Java 8.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.