June 01, 2005

Calendar.roll: I'm so stupid :)

So I just spent about 10 minutes wondering why my unit tests were failing when they have been working for the past 3 weeks, ever since being written actually.

The following code:

—— start of code ——

Calendar cal = GregorianCalendar.getInstance();
Date now = cal.getTime();
cal.roll(Calendar.DAY_OF_MONTH, false);
Date then = cal.getTime();
cal.roll(Calendar.DAY_OF_MONTH, true);
cal.roll(Calendar.DAY_OF_MONTH, true);
Date future = cal.getTime();

ArchivedFile fileA = new ArchivedFileImpl(new File(""), then, "");
ArchivedFile fileB = new ArchivedFileImpl(new File(""), now, "");
ArchivedFile fileC = new ArchivedFileImpl(new File(""), future, "");

SortedSet files = new TreeSet();

ArchivedFile[] orderedFiles = files.toArray(new ArchivedFile[] {});
assertEquals("most recent", fileC, orderedFiles[0]);
assertEquals("middle", fileB, orderedFiles[1]);
assertEquals("oldest", fileA, orderedFiles[2]);

—— end of code ——

was testing that ArchivedFileImpl was correctly sorted based on date.

Spot the problem? It is because roll does not increment other fields, so if you are on the last day of the month and roll 1, you stay on the same month, but go to the first day, so 31st June, rolled by 1 becomes 1st June!

So my code was fine, my unit test was dodgy :) :)

The answer BTW (which is crystal clear if you read the docs) is to call Calendar.add.

As an aside, "roll" kind of implies a knock on effect, "add" doesn't imply anything, so I would have expected the behaviour to be opposite. Oh well.

P.S. The reason I am so stupid is because I have run into this "problem" before :)

- No comments Not publicly viewable

Add a comment

You are not allowed to comment on this entry as it has restricted commenting permissions.

June 2005

Mo Tu We Th Fr Sa Su
May |  Today  | Jul
      1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30         

Search this blog



Most recent comments

  • Interesting… While I'm not completely convinced in such microbenchmarks, I'm pretty sure that 1ms … by Alexander Snaps on this entry
  • Hello. I bought the book yesterday. I was trying to find the source code for chapter 11 and chapter … by Suleman on this entry
  • http://woosight.net/account/login?username=demo by live mashup demo on this entry
  • Thanks mate ….. This blog was really helpful. by Maaz Hurzuk on this entry
  • Ty. Not directly helpful for my problem, but pointed me in the right direction. You will also get th… by Mike E. on this entry

Blog archive

Not signed in
Sign in

Powered by BlogBuilder