tags:

views:

3410

answers:

4

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 awkward to use. What I really need is something like this pseudocode:

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

Not sure if it's relevant, but the dates I'm pulling from the database have timestamps.

+5  A: 
boolean isWithinRange(Date testDate) {
   return !(testDate.before(startDate) || testDate.after(endDate));
}

Doesn't seem that awkward to me. Note that I wrote it that way instead of

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

so it would work even if testDate was exactly equal to one of the end cases.

Paul Tomblin
+2  A: 

An easy way is to convert the dates into milliseconds after January 1, 1970 (use Date.getTime()) and then compare these values.

Rahul
+2  A: 

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.

MBCook
+3  A: 

Consider using Joda Time. I love this library and wish it would replace the current horrible mess that are the existing Java Date and Calendar classes. It's date handling done right.

Ben Hardy
don't you believe introducing Joda Time to a project is over time if all one wants to do is make a simple comparison as the questioner indicated?-
hhafez
I assume you mean overkill. In the case of most library additions I would agree with you. However Joda Time is pretty light, and helps you write more correct date handling code thanks to the immutability of its representations, so it's not a bad thing to introduce in my opinion.
Ben Hardy
And let's not forget StackOverflow rule #46: If anybody mentions dates or times in Java, it's mandatory for somebody to suggest switching to Joda Time. Don't believe me? Try to find a question that doesn't.
Paul Tomblin