How to Check if a Date is Between Two Dates in Java (Date, LocalDate, Instant)
Suppose we want to check if some date
is within a specified range.
Dates often employ the Half-Open rule, where the start date is inclusive and the end date is exclusive.
Let’s take a look at how we can check exclusive, inclusive, and half-open date ranges with LocalDate
.
As of Java 8,
LocalDate
is the standard way to specify a year, month, day value. Feel free to read up on how to convert fromDate
toLocalDate
in Java.
1. Exclusive date range: (start, end)
LocalDate::isAfter
and LocalDate::isBefore
check that some LocalDate
is strictly later than or strictly earlier than another, respectively.
boolean isBetweenExclusive(LocalDate date, LocalDate start, LocalDate end) {
return date.isAfter(start) && date.isBefore(end);
}
If date
is equal to either start
or end
, this function will evaluate to false
.
If we’re working with
Instant
, we can useInstant::isAfter
andInstant::isBefore
. If we’re working withDate
, we can useDate::after
andDate::before
.
2. Inclusive date range: [start, end]
Suppose we want both sides of the date range to be inclusive. We can flip the operator on the LocalDate
objects and negate each expression.
boolean isBetweenInclusive(LocalDate date, LocalDate start, LocalDate end) {
return !date.isBefore(start) && !date.isAfter(end);
}
We’re utilizing the exclusivity of LocalDate::isAfter
and LocalDate::isBefore
to employ an inclusive range by negating the expression.
3. Half-Open date range: [start, end)
To perform a check over a Half-Open interval, we can use one expression from each function above.
boolean isBetweenHalfOpen(LocalDate date, LocalDate start, LocalDate end) {
return !date.isBefore(start) && date.isBefore(end);
}
Here, we’re checking that date
is between a start date, inclusive, and end date, exclusive.