Can anyone please help me understand why I am getting different month values for
SimpleDateFormat dateFormat = new SimpleDateFormat(\"dd/MM/yyyy\");
Syst
Months in Calendar starts in 0
Calendar.MONTH return 0-based values i.e. JANUARY is represented with 0. That way SEPTEMBER is 8.
Your likely problem is that Calendar uses a zero-based index for months. So the format correctly outputs 9
for September, but the getter returns 8
.
Is this stupid and inconsistent of Calendar? Yes! Use the Joda-Time API for working with dates and times instead. As far as I'm aware, it's currently the de-facto standard until JSR 310 comes around.
The other answers are correct. The java.util.Calendar class uses zero-based counting for month numbers. One of many reasons to avoid using the java.util.Date/Calendar classes.
This kind of work is easier with the Joda-Time 2.3 library. Thankfully it sensibly uses one-based counting such as January = 1, December = 12.
java.util.Calendar cal = java.util.Calendar.getInstance();
// Though not required here for this one purpose, it's better to specify a time zone than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( cal.getTime(), timeZone );
// Extract month. Note how these two lines call similar sounding methods that are actually quite different.
// One returns a primitive int value. The other returns an object of nested class DateTime.Property.
int monthNumber = dateTime.getMonthOfYear();
String monthName = dateTime.monthOfYear().getAsText( Locale.FRENCH );
Dump to console…
System.out.println( "dateTime: " + dateTime );
System.out.println( "monthNumber: " + monthNumber );
System.out.println( "monthName: " + monthName );
When run…
dateTime: 2014-02-10T02:58:35.386-05:00
monthNumber: 2
monthName: février
In Calendar class, MONTH start from index 0
. So, January
is 0, February
is 1, and hence September
is 8.
P.S.: - That's true that this is an Inconsistency
in Calendar
class, so I would suggest you to take a look at Joda-Time API to make your life easier while working with date-time data.