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.
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html

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();
//DO NOT DO THIS!!
lastMidnight.set( Calendar.HOUR, lastMidnight.getMinimum(Calendar.HOUR_OF_DAY ));
...snip...


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


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


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));

Comments

Popular Posts