I want to write a boolean valued function which returns true if the given LocalDateTime
falls between two specific points in time, false otherwise.
Specific
A simple TemporalQuery
would do the trick:
static class IsWeekendQuery implements TemporalQuery{
@Override
public Boolean queryFrom(TemporalAccessor temporal) {
return temporal.get(ChronoField.DAY_OF_WEEK) >= 5;
}
}
It would be called like this (using .now()
to get a value to test):
boolean isItWeekendNow = LocalDateTime.now().query(new IsWeekendQuery());
Or, specifically in UTC time (using .now()
to get a value to test):
boolean isItWeekendNow = OffsetDateTime.now(ZoneOffset.UTC).query(new IsWeekendQuery());
Going beyond your question, there is no reason to create a new instance of IsWeekendQuery
every time it is used, so you might want to create a static final TemporalQuery
that encapsulates the logic in a lambda expression:
static final TemporalQuery IS_WEEKEND_QUERY =
t -> t.get(ChronoField.DAY_OF_WEEK) >= 5;
boolean isItWeekendNow = OffsetDateTime.now(ZoneOffset.UTC).query(IS_WEEKEND_QUERY);