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


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

Duration類plusDays()方法

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

用法:

    public Duration plusDays(long day_val);

參數:

  • long day_val– 表示要添加到此 Duration 的天值。

返回值:

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

例:

// Java program to demonstrate the example 
// of plusDays(long day_val) method of Duration

import java.time.*;

public class PlusDaysOfDuration {
    public static void main(String args[]) {
        long days = 2;

        // Instantiates two Duration objects
        Duration du1 = Duration.ofDays(3);
        Duration du2 = Duration.parse("P2DT20M");

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

        System.out.println();

        // adds the given duration in days with this
        // Duration du1 and returns the Duration 
        // i.e. here we are adding the given 2 days 
        // with this du1 that holds the value of 3 days 
        // i.e.( 72 hrs + 48 hrs = 120 hrs )
        Duration plus_val = du1.plusDays(days);

        // Display plus_val
        System.out.println("du1.plusDays(days):" + plus_val);

        // adds the given duration in days with this 
        // Duration du2 and returns the Duration 
        // i.e. here we are adding the given 2 days 
        // with this du2 that holds the value of 2D:20M 
        // i.e.( 48 hrs + 48 hrs = 96 hrs )
        plus_val = du2.plusDays(days);

        // Display plus_val
        System.out.println("du2.plusDays(days):" + plus_val);
    }
}

輸出

du1:PT72H
du2:PT48H20M
days to add:2

du1.plusDays(days):PT120H
du2.plusDays(days):PT96H20M


相關用法


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