Check that date is within a given range of date inclusive

22,524

Solution 1

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

Solution 2

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

Solution 3

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;
}
Share:
22,524
Tian Na
Author by

Tian Na

20 21 Lives Will Be Changed.

Updated on October 20, 2020

Comments

  • Tian Na
    Tian Na over 3 years

    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
    Tian Na over 7 years
    Thank you for answer this is for java.util.Date