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

后端 未结 12 687
耶瑟儿~
耶瑟儿~ 2020-11-22 16:39

I have a series of ranges with start dates and end dates. I want to check to see if a date is within that range.

Date.before() and Date.after() seem to be a little a

12条回答
  •  广开言路
    2020-11-22 17:13

    This was clearer to me,

    // declare calendar outside the scope of isWithinRange() so that we initialize it only once
    private Calendar calendar = Calendar.getInstance();
    
    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
    
    }
    

提交回复
热议问题