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


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


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

用法:

public Duration withSeconds(long amountOfSeconds)

參數:此方法接受參數amountOfSeconds,即秒數。


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

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

示例1:

// Java code to illustrate withSeconds() method 
  
import java.time.Duration; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the amount of seconds 
        long amountOfSeconds = 300; 
  
        // Duration using parse() method 
        Duration duration 
            = Duration.parse("P2DT3H4M"); 
  
        // Get the duration in seconds 
        // using withSeconds() method 
        System.out.println(duration 
                               .withSeconds(amountOfSeconds)); 
    } 
}
輸出:
PT5M

示例2:

// Java code to illustrate withSeconds() method 
  
import java.time.Duration; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Get the amount of seconds 
        long amountOfSeconds = 3000; 
  
        // Duration using ofHours() method 
        Duration duration 
            = Duration.ofHours(5); 
  
        // Get the duration in seconds 
        // using withSeconds() method 
        System.out.println(duration 
                               .withSeconds(amountOfSeconds)); 
    } 
}
輸出:
PT50M

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



相關用法


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