Search code examples
javatime

How to check if a given time is between two other times, when the range includes midnight?


Given two LocalTime instances indicating the start and end of a time range, how can I check if a third LocalTime is between the other two?

Baeldung offers this solution:

LocalTime startTime = LocalTime.parse("09:00:00");
LocalTime endTime = LocalTime.parse("17:00:00");
LocalTime targetTime = LocalTime.parse("12:30:00");
assertTrue(!targetTime.isBefore(startTime) && !targetTime.isAfter(endTime))

However, I find that it doesn't work in the case where the time range spans midnight. For example, if my time range is from 9:00pm to 5:00am, and the target time is 12:30am or 11:30pm, that expression (!targetTime.isBefore(startTime) && !targetTime.isAfter(endTime)) would evaluate to false.

I'm looking for a short and sweet one-liner to cover both situations: when the start and end times include midnight or exclude it.


Solution

  • You current check only works if startTime < endTime. So you just need to check the other case when startTime > endTime.

    Surprisingly, the only change in the range-logic turns out to be just swapping && with || (unless I'm missing something).

    For example like this:

    public boolean isBetween(LocalTime start, LocalTime end, LocalTime target) {
        return start.isAfter(end)
            ? !target.isBefore(start) || !target.isAfter(end)
            : !target.isBefore(start) && !target.isAfter(end);
    }