Increasing Decreasing calendar fields
suggest changeadd() and roll() can be used to increase/decrease Calendar fields.
Calendar calendar = new GregorianCalendar(2016, Calendar.MARCH, 31); // 31 March 2016
add changes the date the way adding or subtracting a real span does, and it can change larger fields:
calendar.add(Calendar.MONTH, -6);
That removes six months. 31 March 2016 becomes 30 September 2015. September has no 31st, so the day is clamped to 30.
roll changes one field and leaves larger fields alone. It still clamps a day that is impossible in the resulting month. Call it on a fresh calendar. The object above is already September 2015, and rolling that object by another six months lands in March 2015.
Calendar rolled = new GregorianCalendar(2016, Calendar.MARCH, 31);
rolled.roll(Calendar.MONTH, -6); // 30 September 2016; the year stays 2016
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents