Alex Rivera | Logout

Calendar returns wrong month

Asked 2009-11-18T10:53:55.637
119
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?

Edit
Report

1 Answer

25

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.

answered 2009-11-18T11:00:13.853

Your Answer