kjl kjl - 1 year ago 78
Java Question

android.util.GregorianCalendar: will c.add(Calendar.DAY_OF_MONTH, 1) rollback or forward?

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download