📜  Java中 Nanos(long) 方法的持续时间及示例

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

Java中 Nanos(long) 方法的持续时间及示例

Java.time 包Duration 类ofNanos(long)方法用于获取 1 纳秒格式的持续时间。

句法:

public static Duration ofNanos(long nanoSeconds)

参数:此方法接受参数nanoSeconds ,它是 nanoSeconds 的数量。它可以是积极的或消极的。

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

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

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

示例 1:

// Java code to illustrate ofNanos() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // input number of Nanos
        long noOfNanos = 1000000;
  
        // Duration using ofNanos() method
        Duration duration
            = Duration.ofNanos(noOfNanos);
  
        System.out.println(duration.getSeconds());
    }
}
输出:
0

示例 2:

// Java code to illustrate ofNanos() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // input number of Nanos
        long noOfNanos = -1000000;
  
        // Duration using ofNanos() method
        Duration duration
            = Duration.ofNanos(noOfNanos);
  
        System.out.println(duration.getSeconds());
    }
}
输出:
-1

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