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


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


java.time包中的Duration Class的ofSeconds(long,long)方法用於獲取1秒格式的持續時間。在這種方法中,以1秒的格式,即每秒1秒,將秒計算為總秒數。第二個參數nanoAdjustment用於以nanoSeconds單位調整秒數。

用法:

public static Duration ofSeconds(long seconds, long nanoAdjustment)

參數:此方法接受兩個參數:


  • seconds:秒數。它可以是正數或負數。
  • nanoAdjustment:這是要在幾秒鍾內進行的調整。

返回值:此方法返回以1秒格式表示時間的Duration。

異常:如果輸入的秒數超過Duration的容量,則此方法將引發ArithmeticException。

以下示例說明了Duration.ofSeconds()方法:

範例1:

// Java code to illustrate ofSeconds() method 
  
import java.time.Duration; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // input number of Seconds 
        long noOfSeconds = 214545; 
  
        // input nanoSeconds adjustment to be made 
        long nanoSecAdjust = 10000; 
  
        // Duration using ofSeconds() method 
        Duration duration 
            = Duration.ofSeconds(noOfSeconds); 
        Duration duration1 
            = Duration.ofSeconds(noOfSeconds, 
                                 nanoSecAdjust); 
  
        System.out.println("Duration without adjustment:"
                           + duration.getSeconds()); 
        System.out.println("Duration with adjustment:"
                           + duration1.getSeconds()); 
    } 
}
輸出:
Duration without adjustment:214545
Duration with adjustment:214545

範例2:

// Java code to illustrate ofSeconds() method 
  
import java.time.Duration; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // input number of Seconds 
        long noOfSeconds = 214545; 
  
        // input nanoSeconds adjustment to be made 
        long nanoSecAdjust = -10000; 
  
        // Duration using ofSeconds() method 
        Duration duration 
            = Duration.ofSeconds(noOfSeconds); 
        Duration duration1 
            = Duration.ofSeconds(noOfSeconds, 
                                 nanoSecAdjust); 
  
        System.out.println("Duration without adjustment:"
                           + duration.getSeconds()); 
        System.out.println("Duration with adjustment:"
                           + duration1.getSeconds()); 
    } 
}
輸出:
Duration without adjustment:214545
Duration with adjustment:214544

參考: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#ofSeconds-long-long-



相關用法


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