Same arguments passed on the same method for the same object. It usually will display true, which is what I expect. But… sometimes it displays false. About 2-3 out of 100 times. What is wrong with this method that would be causing this behavior?
year, month, and day are instance variables containing “2012”, “4”, “1” respectively.
public boolean isInDateRange(String startDate, String endDate)
{
if(startDate == null || endDate == null){
return false;
}
Calendar today = Calendar.getInstance();
today.set(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day));
Calendar start = Calendar.getInstance();
//subtract 1 from the month parameter because java.util.Calendar's months
//go from 0 to 11 instead of 1 to 12.
start.set(Integer.valueOf(startDate.substring(0, 4)), Integer.valueOf(startDate.substring(5, 7)) - 1, Integer.valueOf(startDate.substring(8, 10)));
Calendar end = Calendar.getInstance();
end.set(Integer.valueOf(endDate.substring(0, 4)), (Integer.valueOf(endDate.substring(5, 7))) -1 , Integer.valueOf(endDate.substring(8, 10)));
return today.compareTo(start) >= 0 && today.compareTo(end) <= 0;
}
And here is what I am passing to it
calendarDetails.getTuesday().isInDateRange("2012-05-01 00:00:00", "2012-05-01 00:00:00")
You’re ignoring the time in your calculations. On the few occasions that the millisecond ticks over between
Calendar today = ...andCalendar start = ..., you end up withtoday,start, andendhaving the same value for the date, but the time of bothstartandendis ahead oftoday. Specifically, they’re 1 ms ahead since you’re usingCalendar.getInstance(), which returns the current time, to build all three of them. So when that tick happens,todayisn’t betweenstartandend. You should zero out the time if you don’t care about it.