Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 613
wufoo Avatar asked Dec 31 '12 10:12

wufoo


2 Answers

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
like image 109
assylias Avatar answered Sep 27 '22 21:09

assylias


You need something like:

c2.set(Calendar.DAY_OF_MONTH, 1)

as today's DAY_OF_MONTH (31) happens to be a day that is not in November :-)

like image 34
7zark7 Avatar answered Sep 27 '22 19:09

7zark7