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-
相關用法
- Java Duration minusDays(long)用法及代碼示例
- Java Duration minusHours(long)用法及代碼示例
- Java Duration plus(long, TemporalUnit)用法及代碼示例
- Java Duration plusDays(long)用法及代碼示例
- Java Duration withNanos(long)用法及代碼示例
- Java Duration dividedBy(long)用法及代碼示例
- Java Duration multipliedBy(long)用法及代碼示例
- Java Duration ofNanos(long)用法及代碼示例
- Java Duration ofMillis(long)用法及代碼示例
- Java Duration of(long, TemporalUnit)用法及代碼示例
- Java Duration ofHours(long)用法及代碼示例
- Java Duration ofMinutes(long)用法及代碼示例
- Java Duration ofDays(long)用法及代碼示例
- Java Duration withSeconds(long)用法及代碼示例
- Java Duration minusSeconds(long)用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Duration ofSeconds(long, long) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。