如果日历是该月的最后一天(例如 7 月 31 日),则会
c.add(Calendar.DAY_OF_MONTH, 1);
将 c 设置为同月(七月)的开始,还是会将 c 提前到下个月(八月)?
最佳答案
查看父类(super class)java.util.Calendar
的文档,在名为“字段操作”的部分中(强调我的):
add(f, delta)
addsdelta
to fieldf
. This is equivalent to callingset(f, get(f) + delta)
with two adjustments:Add rule 1. The value of field
f
after the call minus the value of fieldf
before the call isdelta
, modulo any overflow that has occurred in fieldf
. 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)
addsdelta
to fieldf
without changing larger fields. This is equivalent to callingadd(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 thanHOUR
.
因此,roll(Calendar.DAY_OF_MONTH, 1)
会将 7 月 31 日更改为7 月 1 日。
关于java - android.util.GregorianCalendar : will c. add(Calendar.DAY_OF_MONTH, 1) 回滚还是前进?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38407486/