Java中的duration negated()方法

可以使用Java中的Duration类中的negated()方法来获得一个否定了持续时间的不变副本。此方法不需要任何参数,并且返回取反的持续时间。另外,如果发生数字溢出,则会引发ArithmeticException。

演示此的程序如下所示-

示例

import java.time.Duration;
public class GFG {
   public static void main(String[] args) {
      Duration d = Duration.ofHours(1);
      System.out.println("The duration is: " + d);
      System.out.println("A copy with negated duration is: " + d.negated());
   }
}

输出结果

The duration is: PT1H
A copy with negated duration is: PT-1H

现在让我们了解上面的程序。

使用negated()方法可获得一个否定的持续时间不变副本。然后显示。演示这的代码片段如下-

Duration d = Duration.ofHours(1);
System.out.println("The duration is: " + d);
System.out.println("A copy with negated duration is: " + d.negated());