java.time.Period normalize() 更改月份字段的符号和值,尽管其绝对值小于 12

java.time.Period normalize() changes sign and value of month field despite having absolute value less than 12

对于 normalize() 的 Java se 8 API 读取:

This normalizes the years and months units, leaving the days unit unchanged. The months unit is adjusted to have an absolute value less than 11, with the years unit being adjusted to compensate. For example, a period of "1 Year and 15 months" will be normalized to "2 years and 3 months". The sign of the years and months units will be the same after normalization. For example, a period of "1 year and -25 months" will be normalized to "-1 year and -1 month".

  public static void main(String[] args) {
    Consumer<Period> nlz = d -> System.out.println(d.normalized());
    nlz.accept(Period.of( 50, 10, -100));  // case 1
    nlz.accept(Period.of(-50, 10, -100));  // case 2
  }

/*
program output
--------------
P50Y10M-100D
P-49Y-2M-100D
*/

情况一:月单位的绝对值是10,保持不变

情况2:月单位的绝对值是10,但改为-2。

我认为你误读了“标准化后年月单位的符号将相同”。这并不意味着年月号都将保持不变,这意味着生成的年号将与生成的月号相同。

所以在你的第二个例子中,10个月必须调整为负数。这是一个模数 12 运算,结果为负且绝对值小于 12:10-12=-2.

然后调整年份值以保持同期。