We are using Calendar.roll to either move the dates up or down. The javadoc mentions that the larger fields are not modified (i.e. if we move the date by 5 to the left starting on the first day of the month, unfortunately the calendar.getTime() doesn't get me a value from the previous month). The month value remains unchanged, how do I change this behavior. I really would like to move the date value as appropriate. (e.g. If I moved 5 days to the left on Aug 1st, 2010 - I would want to see Jun 27th, 2010 instead of Aug 27th, 2010). What am I missing here?
You will need to use add(Calendar.DATE, -5)
method from Calendar
because of roll rule check.
roll
method is described as :
Add to
field
a signed amount without changing larger fields. A negative roll amount means to subtract from field without changing larger fields.Example: Consider a
GregorianCalendar
originally set to August 31, 1999. Callingroll(Calendar.MONTH, 8)
sets the calendar to April 30, 1999. Using a GregorianCalendar, theDAY_OF_MONTH
field cannot be 31 in the month April.DAY_OF_MONTH
is set to the closest possible value, 30. TheYEAR
field maintains the value of 1999 because it is a larger field thanMONTH
.Example: Consider a
GregorianCalendar
originally set to Sunday June 6, 1999. Callingroll(Calendar.WEEK_OF_MONTH, -1)
sets the calendar to Tuesday June 1, 1999, whereas callingadd(Calendar.WEEK_OF_MONTH, -1)
sets the calendar to Sunday May 30, 1999. This is because the roll rule imposes an additional constraint: TheMONTH
must not change when theWEEK_OF_MONTH
is rolled. Taken together with add rule 1, the resultant date must be between Tuesday June 1 and Saturday June 5. According to add rule 2, theDAY_OF_WEEK
, an invariant when changing theWEEK_OF_MONTH
, is set to Tuesday, the closest possible value to Sunday (where Sunday is the first day of the week).