Tuesday, November 25, 2008

Calendar and date ranges

I hate Java's Calendar and Date apis.  Hopefully JSR 310 will improve things.  

In the meantime, here's a trick for selecting based on a date range :

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, (cal.get(Calendar.HOUR) - 1));
beforeDate = cal.getTime();
cal.set(Calendar.DATE, (cal.get(Calendar.DATE) - 1));
cal.set(Calendar.HOUR_OF_DAY, 00);
cal.set(Calendar.MINUTE, 00);
cal.set(Calendar.SECOND, 00);
afterDate = cal.getTime();
The beforeDate member variable is set to the current date minus one hour.  Then the cal Calendar instance is set to 12:00 AM the day before.

No comments: