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


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

Duration類plus()方法

用法:

    public Duration plus(Duration d);
    public Duration plus(long amt, TemporalUnit t_unit);
  • plus() 方法可在java.time包。
  • plus(Duration d) 方法用於將給定的 Duration 添加到此 Duration 並返回 Duration。
  • plus(long amt, TemporalUnit t_unit) 方法用於將給定單位的給定數量添加到此 Duration 並返回 Duration。
  • 這些方法在執行加法時可能會拋出異常。
    算術異常:當計算結果超出表示此對象的限製時,可能會拋出此異常。
  • 這些是非靜態方法,可以通過類對象訪問,如果我們嘗試使用類名訪問這些方法,則會出現錯誤。

參數:

  • 在第一種情況下,加上(持續時間 d),
    • Duration d- 表示要添加到此持續時間的持續時間。
  • 在第一種情況下,plus(long amt, TemporalUnit t_unit),
    • long amt- 表示要添加到此 Duration 中的數量(以單位為單位)。
    • TemporalUnit t_unit- 表示計量給定數量的單位。

返回值:

在這兩種情況下,方法的返回類型都是Duration

  • 在第一種情況下,它將保存 value-added 給定持續時間的 Duration 返回到此 Duration。
  • 在第二種情況下,它將保持 value-added 單位中給定數量的 Duration 返回到此 Duration。

例:

// Java program to demonstrate the example 
// of plus() method of Duration

import java.time.*;
import java.time.temporal.*;

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

        // Instantiates two Duration objects
        Duration du1 = Duration.ofMinutes(3);
        Duration du2 = Duration.parse("P2DT2H20M20S");

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

        System.out.println();

        // adds the given duration du1
        // with this Duration du2 and returns
        // the Duration i.e. here we are adding
        // the given 3 minutes with this du2 
        // that holds the value of 2D:2H:20M:20S
        Duration plus_val = du1.plus(du2);

        // Display plus_val
        System.out.println("du1.plus(du2):" + plus_val);

        // adds the given amount  in the given unit 
        // with this Duration  and returns the Duration i.e. 
        // here we are adding the amt 10 in minutes unit 
        // with this du2 that holds the value of 2D:2H:20M:20S
        plus_val = du2.plus(amt, ChronoUnit.MINUTES);

        // Display plus_val
        System.out.println("du2.plus(amt,ChronoUnit.MINUTES):" + plus_val);
    }
}

輸出

du1:PT3M
du2:PT50H20M20S
amt to add:10

du1.plus(du2):PT50H23M20S
du2.plus(amt,ChronoUnit.MINUTES):PT50H30M20S


相關用法


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