Java中的持续时间 toNanos() 方法和示例
使用Java.time 包中Duration 类的toNanos()方法获取此持续时间的值,以纳秒数为单位。
句法:
public long toNanos()
参数:此方法不接受任何参数。
返回值:此方法返回一个长值,它是此持续时间的纳秒数。
下面的示例说明了 Duration.toNanos() 方法:
示例 1:
// Java code to illustrate toNanos() method
import java.time.Duration;
public class GFG {
public static void main(String[] args)
{
// Duration using parse() method
Duration duration
= Duration.parse("P2DT3H4M");
System.out.println("Duration: "
+ duration);
// Get the number of nano-seconds
// using toNanos() method
System.out.println(duration.toNanos());
}
}
输出:
Duration: PT51H4M
183840000000000
示例 2:
// Java code to illustrate toNanos() method
import java.time.Duration;
public class GFG {
public static void main(String[] args)
{
// Duration using ofNanos() method
Duration duration
= Duration.ofNanos(10);
System.out.println("Duration: "
+ duration);
// Get the number of nano-seconds
// using toNanos() method
System.out.println(duration.toNanos());
}
}
输出:
Duration: PT0.00000001S
10
参考: https://docs.oracle.com/javase/9/docs/api/ Java/time/Duration.html#toNanos–