當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Duration withNanos(long)用法及代碼示例


java.time包中的Duration Class的withNanos(long)方法用於獲取此持續時間的不可變副本,並將指定的納秒量作為參數傳遞。

用法:

public Duration withNanos(long amountOfNanos)

參數:此方法接受參數納秒數的數量OfNanos。


返回值:此方法返回作為參數傳遞的納秒持續時間。

異常:如果納秒無效,則此方法引發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-



相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Duration withNanos(long) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。