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

标签 java java-time period

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/

相关文章:

java - 如何将一个持续时间除以另一个持续时间?

r - 使用 dplyr spread 后润滑周期变得困惑

java - Libgdx box2d ContactListener 非常有问题

java-8 - java.time.format.DateTimeParseException : Text could not be parsed at index 3

Java 8 - ZonedDateTime 的 DateTimeFormatter 和 ISO_INSTANT 问题

c++ - ALSA 在中断前占用 1024 个缓冲区

java - 确定模式给出的时间范围

JAVAFX 列未填充字符串

java - 生成二叉树形式N aire Tree-递归方法不起作用

java - 为什么我的按钮没有出现在我的 JPanel 上 - Java