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


4 Responses to “java.util.Calendar.roll() works in mysterious ways…”  

  1. 1 Dale

    Hahaha… I think everyone goes through that one at some point in their java career.

  2. 2 Dale

    oh…and I suspect roll() was intended for use in a date/time picking widget…so if you click 22..23..0 on the hour it doesnt change the day. From way back in the day when people wrote actual UI code and built client apps. I guess that was Web -1.0?

  3. 3 chad

    I guess, but doesn’t the name ‘roll’ give you the idea that it will roll the date properly?

    Yes it seems java apps have been replaced by Flash in the “web 2.0″ world. And for good reason!

  4. 4 Owen

    (buries face in hands and cries)

Leave a Reply



Twitter Status



via Twitter