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
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
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With