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

  |   0 评论   |   80 浏览


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

    • java.util.JapaneseImperialCalendar

    • java.util.GregorianCalendar

    • sun.util.BuddhistCalendar


    case DAY_OF_MONTH: // synonym of DATE
    case DAY_OF_YEAR:
    case DAY_OF_WEEK:

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

    calendar.add(Calendar.DAYOFMONTH, 100);

    可以看到最终结果的 dayofyear 还是增长了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
    DAYOFMONTH. 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 超出了 dayofmonth 的范围,这个方法也会正确处理。


    Read The Fucking Source