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

后端 未结 12 670
耶瑟儿~
耶瑟儿~ 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

    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.

提交回复
热议问题