可以使用plusNanos()Java的Duration类中的方法来获取持续时间的不变副本,在其中添加了几纳秒的时间。此方法需要一个参数,即要添加的纳秒数,并且它返回添加了纳秒的持续时间。
演示此的程序如下所示-
import java.time.Duration;
public class Demo {
public static void main(String[] args) {
Duration d = Duration.ofSeconds(1);
System.out.println("The duration is: " + d);
System.out.println("A copy with 100 nano seconds added to the duration is: " + d.plusNanos(100));
}
}输出结果
The duration is: PT1S A copy with 100 nano seconds added to the duration is: PT1.0000001S
现在让我们了解上面的程序。
首先,显示持续时间。然后,使用该plusNanos()方法获得添加了10纳秒的持续时间的不变副本,并将其显示出来。演示这的代码片段如下-
Duration d = Duration.ofSeconds(1);
System.out.println("The duration is: " + d);
System.out.println("A copy with 100 nano seconds added to the duration is: " + d.plusNanos(100));