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());

更新于:30-7-2019

103 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.