views:

76

answers:

3

I have set this calendar in my app:

Calendar cal = Calendar.getInstance();
cal.set(2010, 1, 10); 

I'm using this SimpleDateFormat to get the month as a word:

SimpleDateFormat formatMonth = new SimpleDateFormat("MM");

In one class it comes out as February 10th, 2010.

In another it comes out as March 10th, 2010.

Which is correct?

+6  A: 

The month argument to Calendar.set() is zero-based, so 1 means February. The first behavior is the correct one.

I suspect something in your other class is mistakenly trying to compensate for zero-based month indexes, and that results in an off-by-one error.

Frédéric Hamidi
+1  A: 

Given all the hassles associated with the JDK date handling, you should really be looking to use Joda time instead. The above code would be rewritten as

DateTime dt = new DateTime().withDate(2010,2,10).withTime(12,13,14,0);

and represents 10 February 2010 at 12:13:14.000 in UTC. No ambiguity, thread safe and immutable.

You should note that SimpleDateFormat is not thread safe.

Gary Rowe
Why does it matter if SimpleDateFormat is not thread safe? Where could that cause a problem for example?
kors
It would only cause problems when you've declared it as a static or instance variable so that it's been used among different threads. It's safe if you declare it methodlocal. This has however not much to do with your *actual* problem.
BalusC
+2  A: 

The calendar class has constants for months

 Calendar.JANUARY

for example. You should be using those.

MeBigFatGuy