MadMurf
MadMurf

Reputation: 2323

Java Calendar.set not giving correct result

I can't see where I'm going wrong with the code below, its probably something obvious but I'm too blind to see it at this stage. I'm passing a date of "01/01/2009" to an instance of calendar. I then try and set the month to 2 for March and the output I see is

formatted: 01/01/2009

cal month: 2

cal.set( Calendar.MONTH, mth ); //mth = int 2

log.debug("formatted: " + formatter.format(cal.getTime()));
log.debug("cal month: "+Integer.valueOf(cal.get(Calendar.MONTH)).toString());

When I set the Calendar.DAY to the max value the date comes out as 31/01/2009

Why does my setting of the Month not take?

Upvotes: 2

Views: 5056

Answers (3)

emilebaizel
emilebaizel

Reputation: 4705

We ran into this and the result was that the value you set doesn't get used until you actually try to 'get' the value from Calendar. We were puzzled because using the debugger the value never seemed to get set, but when you actually 'get' it, it works.

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

Getting and Setting Calendar Field Values

The calendar field values can be set by calling the set methods. Any field values set in a Calendar will not be interpreted until it needs to calculate its time value (milliseconds from the Epoch) or values of the calendar fields. Calling the get, getTimeInMillis, getTime, add and roll involves such calculation.

Upvotes: 9

attilla
attilla

Reputation: 1

Perhaps you wanted to use Calendar.DAY_OF_MONTH

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503889

I'll look into exactly what's going on, but the general rule of thumb is: don't use java.util.{Date,Calendar}. Use Joda Time instead... it's so much cleaner...

EDIT: I can't reproduce your issue at the moment. I'd still recommend using Joda, but if you could post a short but complete program to demonstrate the problem, we may be able to work out what's going wrong.

EDIT: Based on another comment, I wonder whether your formatter is wrong... are you really using "dd/mm/yyyy" rather than "dd/MM/yyyy"? "mm" means minutes, not months.

Upvotes: 2

Related Questions