tags:

views:

426

answers:

6
Calendar rightNow = Calendar.getInstance();
String month = String.valueOf(rightNow.get(Calendar.MONTH));

After the execution of the above snippet, month gets a value of 10 instead of 11. How come?

+8  A: 

They start from 0 - check the docs

Bozho
+10  A: 

Months are indexed from 0 not 1 so 10 is November and 11 will be December.

Vincent Ramdhanie
+4  A: 

Months start from zero, like indexes for lists.

Therefore Jan = 0, Feb = 1, etc.

day_trader
+4  A: 

From the API:

The first month of the year is JANUARY which is 0; the last depends on the number of months in a year.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html

Bruno Rothgiesser
+4  A: 

As is clear by the many answers: the month starts with 0.

Here's a tip: you should be using SimpleDateFormat to get the String-representation of the month:

Calendar rightNow = Calendar.getInstance();
java.text.SimpleDateFormat df1 = new java.text.SimpleDateFormat("MM");
java.text.SimpleDateFormat df2 = new java.text.SimpleDateFormat("MMM");
java.text.SimpleDateFormat df3 = new java.text.SimpleDateFormat("MMMM");
System.out.println(df1.format(rightNow.getTime()));
System.out.println(df2.format(rightNow.getTime()));
System.out.println(df3.format(rightNow.getTime()));

Output:

11
Nov
November

Note: the output may vary, it is Locale-specific.

Bart Kiers
+1  A: 

As several people have pointed out, months returned by the Calendar and Date classes in Java are indexed from 0 instead of 1. So 0 is January, and the current month, November, is 10.

You might wonder why this is the case. The origins lie with the POSIX standard functions ctime, gmtime and localtime, which accept or return a time_t structure with the following fields (from man 3 ctime):

int tm_mday;    /* day of month (1 - 31) */
int tm_mon;     /* month of year (0 - 11) */
int tm_year;    /* year - 1900 */

This API was copied pretty much exactly into the Java Date class in Java 1.0, and from there mostly intact into the Calendar class in Java 1.1. Sun fixed the most glaring problem when they introduced Calendar – the fact that the year 2001 in the Gregorian calendar was represented by the value 101 in their Date class. But I'm not sure why they didn't change the day and month values to at least both be consistent in their indexing, either from zero or one. This inconsistency and related confusion still exists in Java (and C) to this day.

Matt Ryall