Java: how do I check if a Date is within a certain range ?

Java: how do I check if a Date is within a certain range ?

Asked on December 26, 2018 in Java.
Add Comment


  • 5 Answer(s)

    Use this code,

    return testDate.after(startDate) && testDate.before(endDate);
    
    

    This will be work even if one of the end cases is equal to testDate .

    Answered on December 26, 2018.
    Add Comment

    The calender works similar to the Date.getTime() function,

    boolean isWithinRange(Date testDate) {
        return testDate.getTime() >= startDate.getTime() &&
                testDate.getTime() <= endDate.getTime();
    }
    

    The Date.getTime()  function will give the number of milliseconds since 1/1/1970 00:00:00 GMT and it is easy to compare with another one.

    Answered on December 26, 2018.
    Add Comment

    Here is the simple and easy solution,

    Math.abs(date1.getTime() - date2.getTime()) ==
        Math.abs(date1.getTime() - dateBetween.getTime()) + Math.abs(dateBetween.getTime() - date2.getTime());
    
    Answered on December 26, 2018.
    Add Comment

    That’s the correct way. Calendars work the same way. The best I could offer you (based on your example) is this:

    boolean isWithinRange(Date testDate) {
        return testDate.getTime() >= startDate.getTime() &&
                 testDate.getTime() <= endDate.getTime();
    }

    Date.getTime() returns the number of milliseconds since 1/1/1970 00:00:00 GMT, and is a long so it’s easily comparable.

    Answered on January 16, 2019.
    Add Comment
    public boolean isWithinRange(Date date, Date startDate, Date endDate) {
    
        calendar.setTime(startDate);
        int startDayOfYear = calendar.get(Calendar.DAY_OF_YEAR); // first day is 1, last day is 365
        int startYear = calendar.get(Calendar.YEAR);
    
        calendar.setTime(endDate);
        int endDayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
        int endYear = calendar.get(Calendar.YEAR);
    
        calendar.setTime(date);
        int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
        int year = calendar.get(Calendar.YEAR);
    
        return (year > startYear && year < endYear) // year is within the range
                || (year == startYear && dayOfYear >= startDayOfYear) // year is same as start year, check day as well
                || (year == endYear && dayOfYear < endDayOfYear); // year is same as end year, check day as well
    
    }
    Answered on January 16, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.