首页  >  问答  >  正文

java - Calendar的add方法中的DAY_OF_MONTH参数和DAY_OF_YEAR参数有什么区别?

比如,

calendar.add(Calendar.DAY_OF_MONTH, amount);
calendar.add(Calendar.DAY_OF_YEAR, amount);

如上,有何区别?

怪我咯怪我咯2766 天前478

全部回复(1)我来回复

  • 黄舟

    黄舟2017-04-17 16:43:59

    简单来说,没区别。

    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:
        break;
    

    粗看一下,break以后的执行分支并没有针对这三种做区别处理。
    而且 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 的范围,这个方法也会正确处理。
    不过从可读性考虑,还是用适当的参数比较好。

    回复
    0
  • 取消回复