I have a Calendar instance that starts with the first day in December. I am trying to set that Calendar instance to the last Tuesday of the year. Somewhere between setting the last day of the year and the day of week, the Calendar instance reverts back to the original time:
Calendar cal = ....;
Log.d(TAG, String.format("Starting here %d-%d-%d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH)));
cal.set(Calendar.DAY_OF_YEAR, cal.getActualMaximum(Calendar.DAY_OF_YEAR));
cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
Log.d(TAG, String.format("Ending here %d-%d-%d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH)));
/* Other stuff */
Gives me this output for 2017 and 2018:
2017:
Starting here 2017-12-1
Ending here 2017-11-28
2018:
Starting here 2018-12-1
Ending here 2018-11-27
An Unsatisfying Fix
However, if I retrieve data from the Calendar instance, it works fine:
Calendar cal = ....;
Log.d(TAG, String.format("Starting here %d-%d-%d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH)));
cal.set(Calendar.DAY_OF_YEAR, cal.getActualMaximum(Calendar.DAY_OF_YEAR));
// Ask the Calendar instance for information
long dummyValue = cal.getTimeInMillis();
cal.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
Log.d(TAG, String.format("Ending here %d-%d-%d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH)));
/* Other stuff */
Gives me this output for 2017 and 2018:
2017:
Starting here 2017-12-1
Ending here 2018-1-2
2018:
Starting here 2018-12-1
Ending here 2019-1-1
And yes, I know the dates for the second set of values are not the last Tuesday. That's what /* Other stuff */
is for.