5

This question is to compare dates inclusively in Java.

Is there a better way to check if a given date is within a range inclusively?

Date startDate, endDate, dateToCheck;

if ( dateToCheck.equals(startDate) || 
     dateToCheck.equals(endDate) || 
    (dateToCheck.after(startDate) && dateToCheck.before(endDate) ) 
Tian Na
  • 846
  • 2
  • 15
  • 30

3 Answers3

10

You can avoid the equals checks by checking that the given date is not before or after the range :

if (!dateToCheck.before (startDate) && !dateToCheck.after (endDate))
Eran
  • 387,369
  • 54
  • 702
  • 768
6

If you are using Joda DateTime there is a specific method you can use from the Interval class: interval.contains(date). You can convert your Java date very easy to the Joda Interval and DateTime.

See here for more informations about the contains method.

Edit saw your edit just now (I assume that you are using Java Date):

Interval interval = new Interval(startDate.getTime(), endDate.getTime()); interval.contains(dateToCheck.getTime());

smsnheck
  • 1,563
  • 3
  • 21
  • 33
5

You can always use the compareTo method for inclusive date ranges:

public boolean checkBetween(Date dateToCheck, Date startDate, Date endDate) {
    return dateToCheck.compareTo(startDate) >= 0 && dateToCheck.compareTo(endDate) <=0;
}