So I found the behavior of the roll() method inside the java.util.Calendar class a bit odd. The method declaration is:
Where the field can be any attribute of the date. I’m interested in the HOUR field since I need a rolling hourly window.
When you pass the field of HOUR and 1 for the amount, you would expect that to bump the hour up by one, and when it reaches midnight roll over to the next day. Right?
Well here’s what happens:
cal.roll(Calendar.HOUR, 1)Time: Fri Jan 27 10:29:23 PST 2006
Time: Fri Jan 27 11:29:23 PST 2006
Time: Fri Jan 27 00:29:23 PST 2006
Time: Fri Jan 27 01:29:23 PST 2006
Holy crap, it doesn’t even get past noon! After reading the docs a little more closely I’ve found HOUR to be associated with AM/PM and what I really should be using is HOUR_OF_DAY.
Okay here we go:
cal.roll(Calendar.HOUR_OF_DAY, 1)Time: Fri Jan 27 22:37:14 PST 2006
Time: Fri Jan 27 23:37:14 PST 2006
Time: Fri Jan 27 00:37:14 PST 2006
Time: Fri Jan 27 01:37:14 PST 2006
A little closer, but not quite! Why didn’t it roll to the next day? It seems like it should do considering the documentation suggests that.
So after about 20 minutes of dicking around with this, I decided to give the add() method a go. And low and behold it works as one would expect:
cal.add(Calendar.HOUR_OF_DAY, 1)Time: Fri Jan 27 22:41:17 PST 2006
Time: Fri Jan 27 23:41:17 PST 2006
Time: Sat Jan 28 00:41:17 PST 2006
Time: Sat Jan 28 01:41:17 PST 2006
So my question is, what is the purpose of the roll() method? Can someone enlighten me?
Now playing: Morcheba – Slow Down