Java Duration withNanos(long)方法及示例
java.time包中Duration类的withNanos(long)方法用于获取该持续时间的不可变副本,并将指定的纳秒数作为参数传递。
语法。
public Duration withNanos(long amountOfNanos)
参数。该方法接受一个参数 amountOfNanos,它是纳秒的数量。
返回值。该方法返回一个作为参数传递的纳秒数的持续时间。
异常。如果纳秒数无效,该方法会抛出 DateTimeException。
下面的例子说明了Duration.withNanos()方法。
例子1:
// Java code to illustrate withNanos() method
import java.time.Duration;
public class GFG {
public static void main(String[] args)
{
// Get the amount of nano-seconds
int amountOfNanos = 30000;
// Duration using parse() method
Duration duration
= Duration.parse("P2DT3H4M");
// Get the duration in nano-seconds
// using withNanos() method
System.out.println(duration
.withNanos(amountOfNanos));
}
}
输出:
PT51H4M0.00003S
例2:
// Java code to illustrate withNanos() method
import java.time.Duration;
public class GFG {
public static void main(String[] args)
{
// Get the amount of nano-seconds
int amountOfNanos = 100000;
// Duration using ofHours() method
Duration duration = Duration.ofHours(5);
// Get the duration in nano-seconds
// using withNanos() method
System.out.println(duration
.withNanos(amountOfNanos));
}
}
输出:
PT5H0.0001S
参考资料: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#withNanos-int-