Allen 专栏-移动互联网

Calendar 1 标签

Calendar的add方法中的DAY_OF_MONTH参数和DAY_OF_YEAR参数有什么区别? 有更新!


Calendar 类的 add 方法是个抽象方法,在 JDK 中有三个类实现了这个方法,分别是:

  • java.util.JapaneseImperialCalendar

  • java.util.GregorianCalendar

  • sun.util.BuddhistCalendar


case DAY_OF_MONTH: // synonym of DATE

而且 amount 似乎没有受第一个参数的范围限制,比如调用:

calendar.add(Calendar.DAY_OF_MONTH, 100);

可以看到最终结果的 day_of_year 还是增长了100 天。

这个方法的 API 中描述的两个规则可以解释这种超过范围情况:

Add rule 1. The value of field after the call minus the value of field
before the call is amount, modulo any overflow that has occurred in
field. 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 rule 2. If a smaller field is expected to be invariant, but it is
impossible for it to be equal to its prior value because of changes in
its minimum or maximum after field is changed, then its value is
adjusted to be as close as possible to its expected value. A smaller
field represents a smaller unit of time. HOUR is a smaller field than
DAY_OF_MONTH. No adjustment is made to smaller fields that are not
expected to be invariant. The calendar system determines what fields
are expected to be invariant.

所以我觉得这两个方法调用没有区别,即便 amount 超出了 day_of_month 的范围,这个方法也会正确处理。