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

Viewed 266515

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?

11 Answers

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

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

Another option

min.getTime() <= d.getTime() && d.getTime() <= max.getTime()

you can use getTime() and compare the returned long UTC values.

EDIT if you are sure you'll not have to deal with dates before 1970, not sure how it will behave in that case.

You might want to take a look at Joda Time which is a really good API for dealing with date/time. Even though if you don't really need it for the solution to your current question it is bound to save you pain in the future.

Related