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


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

Duration類of()方法

  • of() 方法可在java.time包。
  • of() 方法用於表示此 Duration 中給定單位 (t_unit) 中的給定數量 (amt)。
  • of() 方法是一個靜態方法,它可以通過類名訪問,如果我們嘗試使用類對象訪問該方法,那麽我們不會得到錯誤。
  • of() 方法在表示 Duration 時可能會拋出異常。
    • 算術異常:當計算結果值超出限製時可能會拋出此異常。
    • 日期時間異常:當給定的單位在持續時間方麵不準確時,可能會拋出此異常。

用法:

    public static Duration of(long amt, TemporalUnit t_unit);

參數:

  • long amt– 表示在給定單位中使用的數量。
  • TemporalUnit t_unit– 表示計量數量的單位。

返回值:

這個方法的返回類型是Duration,它返回以給定單位保存數量 (amt) 值的 Duration。

例:

// Java program to demonstrate the example 
// of of(long amt, TemporalUnit t_unit) method 
// of Duration

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

public class OfDuration {
    public static void main(String args[]) {
        long amt = 2;
        ChronoUnit amt_unit = ChronoUnit.MINUTES;

        // represents the given amount
        // in the given unit i.e here amt 2 is
        // represented in minutes like 2M
        Duration du1 = Duration.of(amt, amt_unit);

        // Display du1
        System.out.println("Duration.of(2,minutes):" + du1);

        amt_unit = ChronoUnit.DAYS;

        // represents the given amount
        // in the given unit i.e. here amt 2 is
        // represented in DAYS like 2D i.e. 48H
        Duration du2 = Duration.of(amt, amt_unit);

        // Display du2
        System.out.println("Duration.of(2,days):" + du2);
    }
}

輸出

Duration.of(2,minutes):PT2M
Duration.of(2,days):PT48H


相關用法


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