📌  相关文章
📜  Java中的 Duration withNanos(long) 方法和示例

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

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-