Can anyone please help me understand why I am getting different month values for
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(cal.getTime())
+ "--"
+ cal.get(Calendar.MONTH));
Surprisingly displays
09/09/2012--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 returns8
.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.
Dump to console…
When run…
In
Calendar
class,MONTH
start from index0
. So,January
is 0,February
is 1, and henceSeptember
is 8.P.S.: - That's true that this is an
Inconsistency
inCalendar
class, so I would suggest you to take a look atJoda-Time API
to make your life easier while working with date-time data.Calendar.MONTH return 0-based values i.e. JANUARY is represented with 0. That way SEPTEMBER is 8.
Months in Calendar starts in 0