Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar roll operation doesn't provide me with the correct output

Tags:

java

calendar

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?

like image 760
user339108 Avatar asked Aug 23 '10 10:08

user339108


2 Answers

You can use Calendar.add with a negative amount.

like image 94
K Erlandsson Avatar answered Sep 21 '22 15:09

K Erlandsson


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. Calling roll(Calendar.MONTH, 8) sets the calendar to April 30, 1999. Using a GregorianCalendar, the DAY_OF_MONTH field cannot be 31 in the month April. DAY_OF_MONTH is set to the closest possible value, 30. The YEAR field maintains the value of 1999 because it is a larger field than MONTH.

Example: Consider a GregorianCalendar originally set to Sunday June 6, 1999. Calling roll(Calendar.WEEK_OF_MONTH, -1) sets the calendar to Tuesday June 1, 1999, whereas calling add(Calendar.WEEK_OF_MONTH, -1) sets the calendar to Sunday May 30, 1999. This is because the roll rule imposes an additional constraint: The MONTH must not change when the WEEK_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, the DAY_OF_WEEK, an invariant when changing the WEEK_OF_MONTH, is set to Tuesday, the closest possible value to Sunday (where Sunday is the first day of the week).

like image 26
YoK Avatar answered Sep 21 '22 15:09

YoK