Thursday, August 13, 2009

GregorianCalendar foolishness

I wanted to add queries to my Grails application to find tasks that needed to be completed today, or were delinquent (due date < last midnight).
My application kept thinking things were delinquent the afternoon of the due date.

The problem was that I neglected to read how HOUR_OF_DAY differed from HOUR and absentmindedly mixed the two.

You can try to set HOUR to 0 but it will default to 12. If it is the afternoon when you request the Calendar object then it will assume you mean 12 noon.

Calendar lastMidnight = Calendar.getInstance();
lastMidnight.set( Calendar.HOUR, lastMidnight.getMinimum(Calendar.HOUR_OF_DAY ));

//this is ok
lastMidnight.set( Calendar.HOUR_OF_DAY, lastMidnight.getMinimum(Calendar.HOUR_OF_DAY ));

//this is also ok
lastMidnight.set( Calendar.AM_PM, Calendar.AM );
lastMidnight.set( Calendar.HOUR, lastMidnight.getMinimum(Calendar.HOUR ));

The other settings are pretty self-explanatory

lastMidnight.set( Calendar.MINUTE, lastMidnight.getMinimum(Calendar.MINUTE));
lastMidnight.set( Calendar.SECOND, lastMidnight.getMinimum(Calendar.SECOND));
lastMidnight.set( Calendar.MILLISECOND,lastMidnight.getMinimum(Calendar.MILLISECOND));

No comments:

Post a Comment