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


Java Duration plusSeconds()用法及代碼示例

Duration類plusSeconds()方法

  • plusSeconds() 方法可在java.time包。
  • plusSeconds() 方法用於將給定的持續時間(以秒為單位)添加到此持續時間並返回持續時間。
  • plusSeconds() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • plusSeconds() 方法可能會在執行加法時拋出異常。
    算術異常:當計算結果超過此 Duration 的長度時,可能會拋出此異常。

用法:

    public Duration plusSeconds(long sec_val);

參數:

  • long sec_val– 表示要添加到此 Duration 的秒值。

返回值:

這個方法的返回類型是Duration,它返回包含將給定秒數添加到此 Duration 的值的 Duration。

例:

// Java program to demonstrate the example 
// of plusSeconds(long sec_val) method of Duration

import java.time.*;

public class PlusSecondsOfDuration {
    public static void main(String args[]) {
        long seconds = 10;

        // Instantiates two Duration objects
        Duration du1 = Duration.ofSeconds(40);
        Duration du2 = Duration.ofMinutes(1);

        // Display du1, du2 
        System.out.println("du1:" + du1);
        System.out.println("du2:" + du2);
        System.out.println("seconds to add:" + seconds);

        System.out.println();

        // adds the given duration in seconds with 
        // this Duration du1 and returns the Duration 
        // i.e. here we are adding the given 10 seconds
        // with this du1 that holds the value of 
        // 40 seconds i.e. 40S + 10S = 50S
        Duration plus_val = du1.plusSeconds(seconds);

        // Display plus_val
        System.out.println("du1.plusSeconds(seconds):" + plus_val);

        // adds the given duration in seconds with 
        // this Duration du2 and returns the Duration 
        // i.e. here we are adding the given 10 seconds
        // with this du2 that holds the value of 
        // 1M i.e. 1M + 10S = 1M 10S
        plus_val = du2.plusSeconds(seconds);

        // Display plus_val
        System.out.println("du2.plusSeconds(seconds):" + plus_val);
    }
}

輸出

du1:PT40S
du2:PT1M
seconds to add:10

du1.plusSeconds(seconds):PT50S
du2.plusSeconds(seconds):PT1M10S


相關用法


注:本文由純淨天空篩選整理自 Java Duration Class | plusSeconds() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。