Monthly Archives: January 2006

java.util.Calendar.roll() works in mysterious ways…

So I found the behavior of the roll() method inside the java.util.Calendar class a bit odd. The method declaration is:

roll(int field, int amount)

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

Time to ski…

I drove up to Tahoe the other night to hang out with Christopher. Last night was spent drinking beer and hacking on a side project we have been working on together. More about that in later posts…

But right now, we are headed out to spend some time on the slopes. Snow has been coming down pretty steadily all morning, so we should be able to get in some good turns.

Now playing: Tom Waits – Chocolate Jesus