Java calendar, getting current month value, clarifications needed

Nov. 1.

Calendar.getInstance().get(Calendar.MONTH); // prints 10 (October) 

It makes sense if we start at 0, but it looks like we are not

  Calendar.getInstance().get(Calendar.JANUARY); // prints 1 

What am I missing, please?

+6
source share
6 answers

Months in the Java calendar are 0-indexed. Calendar.JANUARY is not a "field", so you should not pass it to the get method.

+17
source

as others said Calendar.MONTH returns int and null indexing.

to get the current month as a String method use SimpleDateFormat.format()

 Calendar cal = Calendar.getInstance(); System.out.println(new SimpleDateFormat("MMM").format(cal.getTime())); returns NOV 
+13
source
 Calendar.getInstance().get(Calendar.MONTH); 

is zero, 10 is November. From javadoc;

public static final int MONTH Field number to retrieve and set, indicating the month. This is a calendar value. The first month of the year in Gregorian and Julian calendars is JANUARY, which is 0; the latter depends on the number of months in a year.

 Calendar.getInstance().get(Calendar.JANUARY); 

is not a reasonable thing, the value for JANUARY is 0, which is the same as the ERA , you are really calling;

 Calendar.getInstance().get(Calendar.ERA); 
+11
source

Calendar.get takes one of the standard calendar fields as an argument, for example, YEAR or MONTH not the name of the month.

Calendar.JANUARY is 0, which is also the value of Calendar.ERA , so Calendar.getInstance().get(0) will return an era, in this case Calendar.AD , which is 1.

In the first part of your question, note that, as it is wildly documented, months start at 0, so 10 is actually November.

+3
source
 import java.util.*; class GetCurrentmonth { public static void main(String args[]) { int month; GregorianCalendar date = new GregorianCalendar(); month = date.get(Calendar.MONTH); month = month+1; System.out.println("Current month is " + month); } } 
+1
source

Use Calendar.getInstance().get(Calendar.MONTH)+1 to get the current month.

-1
source

All Articles