android.util.GregorianCalendar: c.add(Calendar.DAY_OF_MONTH, 1) 回退还是前进?

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

如果日历是在该月的最后一天(比如 7 月 31 日),将

c.add(Calendar.DAY_OF_MONTH, 1);

将 c 设置为同月的开始,即 7 月,还是将 c 提前到下个月,即 8 月?

Calendar 对象中的月份从 0 开始。所以 1 表示二月。你知道 2 月的最后一天是 28,所以输出应该是 3 月 2 日。

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

所以

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

查看超类 java.util.Calendar 的文档,在名为“Field Manipulation”的部分(强调我的):

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.

因此 add(Calendar.DAY_OF_MONTH, 1) 会将 7 月 31 日更改为 8 月 1 日

相比之下,文档继续:

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.

因此 roll(Calendar.DAY_OF_MONTH, 1) 会将 7 月 31 日更改为 7 月 1 日