How can I determine if a date is between two dates in Java? [duplicate]
How can I check if a date is between two other dates, in the case where all three dates are represented by instances of java.util.Date
?
Solution 1:
This might be a bit more readable:
Date min, max; // assume these are set to something
Date d; // the date in question
return d.after(min) && d.before(max);
Solution 2:
If you don't know the order of the min/max values
Date a, b; // assume these are set to something
Date d; // the date in question
return a.compareTo(d) * d.compareTo(b) > 0;
If you want the range to be inclusive
return a.compareTo(d) * d.compareTo(b) >= 0;
You can treat null
as unconstrained with
if (a == null) {
return b == null || d.compareTo(b) < 0;
} else if (b == null) {
return a.compareTo(d) < 0;
} else {
return a.compareTo(d) * d.compareTo(b) > 0;
}
Solution 3:
Like so:
Date min, max; // assume these are set to something
Date d; // the date in question
return d.compareTo(min) >= 0 && d.compareTo(max) <= 0;
You can use >
instead of >=
and <
instead of <=
to exclude the endpoints from the sense of "between."