📜  Java中的 Duration ofSeconds(long, long) 方法及示例

📅  最后修改于: 2022-05-13 01:55:09.178000             🧑  作者: Mango

Java中的 Duration ofSeconds(long, long) 方法及示例

Java.time 包Duration 类ofSeconds(long, long)方法用于获取 1 秒格式的持续时间。在此方法中,秒数以 1 秒格式的总秒数计算,即每秒 1 秒。第二个参数 nanoAdjustment 用于调整以 nanoSeconds 为单位的秒数。

句法:

public static Duration ofSeconds(long seconds, long nanoAdjustment)

参数:此方法接受两个参数:

  • seconds :这是秒数。它可以是积极的或消极的。
  • nanoAdjustment :这是要在几秒钟内进行的调整。

返回值:此方法返回一个以 1 秒格式表示时间的Duration

异常:如果输入的秒数超过 Duration 的容量,此方法将抛出ArithmeticException

下面的示例说明了 Duration.ofSeconds() 方法:

示例 1:

// Java code to illustrate ofSeconds() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // input number of Seconds
        long noOfSeconds = 214545;
  
        // input nanoSeconds adjustment to be made
        long nanoSecAdjust = 10000;
  
        // Duration using ofSeconds() method
        Duration duration
            = Duration.ofSeconds(noOfSeconds);
        Duration duration1
            = Duration.ofSeconds(noOfSeconds,
                                 nanoSecAdjust);
  
        System.out.println("Duration without adjustment: "
                           + duration.getSeconds());
        System.out.println("Duration with adjustment: "
                           + duration1.getSeconds());
    }
}
输出:
Duration without adjustment: 214545
Duration with adjustment: 214545

示例 2:

// Java code to illustrate ofSeconds() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // input number of Seconds
        long noOfSeconds = 214545;
  
        // input nanoSeconds adjustment to be made
        long nanoSecAdjust = -10000;
  
        // Duration using ofSeconds() method
        Duration duration
            = Duration.ofSeconds(noOfSeconds);
        Duration duration1
            = Duration.ofSeconds(noOfSeconds,
                                 nanoSecAdjust);
  
        System.out.println("Duration without adjustment: "
                           + duration.getSeconds());
        System.out.println("Duration with adjustment: "
                           + duration1.getSeconds());
    }
}
输出:
Duration without adjustment: 214545
Duration with adjustment: 214544

参考: https://docs.oracle.com/javase/9/docs/api/ Java/time/Duration.html#ofSeconds-long-long-