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

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

    文章转载自 https://segmentfault.com/q/1010000004275325

    Read The Fucking Source

    评论

    发表评论

    validate