0

If the Calendar is on the last day of the month (say 31st of July) , will

c.add(Calendar.DAY_OF_MONTH, 1);

set c to the start of the same month, July, or will it advance c to the next month, August?

kjl
  • 311
  • 3
  • 13

2 Answers2

1

Look at the documentation of the superclass java.util.Calendar, in the section named "Field Manipulation" (emphasis mine):

add(f, delta) adds delta to field f. This is equivalent to calling set(f, get(f) + delta) with two adjustments:

Add rule 1. The value of field f after the call minus the value of field f before the call is delta, modulo any overflow that has occurred in field f. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.

So add(Calendar.DAY_OF_MONTH, 1) will change 31st of July to 1st of August.

In contrast, the documentation continues:

roll(f, delta) adds delta to field f without changing larger fields. This is equivalent to calling add(f, delta) with the following adjustment:

Roll rule. Larger fields are unchanged after the call. A larger field represents a larger unit of time. DAY_OF_MONTH is a larger field than HOUR.

So roll(Calendar.DAY_OF_MONTH, 1) will change 31st of July to 1st of July.

Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Thank you. Perhaps there is some advantage to java lacking a repl. I learned more from your response that I would have from testing. It's also good to know about the roll method. – kjl Jul 16 '16 at 05:15
0

Months in Calendar object start from 0. so 1 means February. And you know february last day is 28 so output should be 2 March.

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

so

Calendar calendar = new GregorianCalendar();

int year       = calendar.get(Calendar.YEAR);
int month      = calendar.get(Calendar.MONTH); 
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); // Jan = 0, not 1
sasikumar
  • 12,540
  • 3
  • 28
  • 48