[java] Java Calendar, getting current month value, clarification needed

On November 1st ..

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

It would make sense if we start with 0, but it appears that we do not

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

What am i missing please?

This question is related to java calendar

The answer is


Months in Java Calendar are 0-indexed. Calendar.JANUARY isn't a field so you shouldn't be passing it in to the get method.


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


as others said Calendar.MONTH returns int and is zero indexed.

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

Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));

returns NOV

Calendar.getInstance().get(Calendar.MONTH);

is zero based, 10 is November. From the javadoc;

public static final int MONTH Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

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

is not a sensible thing to do, the value for JANUARY is 0, which is the same as ERA, you are effectively calling;

Calendar.getInstance().get(Calendar.ERA);

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);
    }
}

Calendar.get takes as argument one of the standard Calendar fields, like YEAR or MONTH not a month name.

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

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