You can use LocalTime for that (since you want it to be independent of the day or timezones or anything like that). It has isBefore
and similar methods that makes this very simple:
public static boolean isBetween(LocalTime before, LocalTime candidate, LocalTime after) {
return before.isBefore(candidate) && candidate.isBefore(after);
}
Usage is simple:
System.out.println(isBetween(LocalTime.of(20, 0), LocalTime.now(), LocalTime.of(23, 0));
Edit
It seems that you actually want another logic that allows for ranges that overlap a day. Your example for this is:
Current time: 01:00, start: 21:00, end: 8:00 -> returns true
To make this possible I would introduce the following changes.
First, you can detect this event by simply checking whether before
is actually before after
. If not, then you have this case. Next, identify whether now
is on the day of before
or after
and then reset the other to either the beginning of the day (00:00
) or the end of the day (23:59
) respectively. Afterwards you can compare again by normal means as shown before:
public static boolean isBetween(LocalTime before, LocalTime candidate, LocalTime after) {
// Special handling for day-overlap
if (before.isAfter(after)) {
// Identify on which day candidate is and reset the other
if (before.isBefore(candidate)) {
after = LocalTime.MAX;
} else {
before = LocalTime.MIN;
}
}
return before.isBefore(candidate) && candidate.isBefore(after);
}