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
*/
情况1:月份单位绝对值为10,保持不变。
情况2:月份单位的绝对值为10,但改为-2。
最佳答案
我认为您误读了“标准化后年份和月份单位的符号将相同。”。这并不意味着年份和月份符号将保持相同,而是意味着生成的年份符号将与生成的月份符号相同。
因此,在第二个示例中,必须将 10 个月调整为负值。这是模 12 运算,结果为负且绝对值小于 12:10-12=-2。
然后调整年份值以保持相同的时期。
关于java.time.Period normalize() 更改月份字段的符号和值,尽管绝对值小于 12,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62647569/