javaandroidcalendar

Unable to set month in Java.util.Calendar


I have an onClickListener in Android which changes the month of a Java.util.Calendar object depending on +/- button clicked. The code to set the calendar is below. It seems I cannot set the month to "10". What in the world is going on here?

Calendar c2 = Calendar.getInstance();
int newmonth = 9;
Log.d (TAG, "month before: "+ c2.get (Calendar.MONTH));
c2.set (Calendar.MONTH, newmonth);
Log.d (TAG, "month now: " + c2.get(Calendar.MONTH));

month before: 11 month now: 9

Calendar c2 = Calendar.getInstance();
int newmonth = 10;
Log.d (TAG, "month before: "+ c2.get (Calendar.MONTH));
c2.set (Calendar.MONTH, newmonth);
Log.d (TAG, "month now: " + c2.get(Calendar.MONTH));

month before: 11 month now: 11


Solution

  • Months start at 0, so 9 is October and 10 is November, and November does not have 31 days.

    If you add:

    Log.d (TAG, "day of month now: " + c2.get(Calendar.DAY_OF_MONTH));
    

    You will see that in your second example the day has moved from 31st to 1st.

    To get the desired behaviour, you should use:

    c2.add(Calendar.MONTH, -1); // or +1