Home  >  Q&A  >  body text

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

比如,

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

如上,有何区别?

怪我咯怪我咯2717 days ago444

reply all(1)I'll reply

  • 黄舟

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

    To put it simply, there is no difference.

    The add method of the Calendar class is an abstract method. There are three classes in the JDK that implement this method, namely:

    • java.util.JapaneseImperialCalendar

    • java.util.GregorianCalendar

    • sun.util.BuddhistCalendar

    Ignore the third one and only look at the first two implementation classes. There is this piece of code:

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

    At a glance, the execution branches after break do not differentiate between these three types.
    And amount does not seem to be limited by the range of the first parameter, such as calling:

    calendar.add(Calendar.DAY_OF_MONTH, 100);

    You can see that day_of_year of the final result still increases by 100 days.

    Two rules described in the API of this method can account for this out-of-range condition:

    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.

    So I think there is no difference between these two method calls. Even if amount exceeds the range of day_of_month, this method will handle it correctly.
    However, from the perspective of readability, it is better to use appropriate parameters.

    reply
    0
  • Cancelreply