How can I determine if a date is between two dates in Java?

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);

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;
}

Between dates Including end points can be written as

public static boolean isDateInBetweenIncludingEndPoints(final Date min, final Date max, final Date date){
    return !(date.before(min) || date.after(max));
}

NB: as @Ponmudi pointed out in the comments, this solution may not work if the dates are different at miilliseconds level.


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."

Tags:

Java

Date