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


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

Duration類get()方法

  • get() 方法可在java.time包。
  • get() 方法用於返回給定單位的值。
  • get() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • get() 方法可能會在為給定單元返回值時拋出異常。
    • 日期時間異常:當給定的 amt 無法轉換為 Duration 時,可能會拋出此異常。
    • 不支持的TemporalTypeException:當給定的單位不受支持時,可能會拋出此異常。

用法:

    public long get(TemporalUnit t_unit);

參數:

  • TemporalUnit t_unit– 表示返回值的時間單位。

返回值:

這個方法的返回類型是long,它返回給定時間單位的值。

例:

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

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

public class GetOfDuration {
    public static void main(String args[]) {
        // Instantiates two Duration objects
        Duration du1 = Duration.ofHours(1);
        Duration du2 = Duration.ofMinutes(5);

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

        // gets the value of the given unit i.e. 
        // here we are requesting the value of 
        // du1 in SECONDS unit
        long get_val = du1.get(ChronoUnit.SECONDS);

        // Display get_val
        System.out.println("du1.get(ChronoUnit.SECONDS):" + get_val);

        // gets the value of the given unit i.e. 
        // here we are requesting the value of 
        // du2 in SECONDS unit
        get_val = du2.get(ChronoUnit.SECONDS);

        // Display get_val
        System.out.println("du2.get(ChronoUnit.SECONDS):" + get_val);
    }
}

輸出

du1:PT1H
du2:PT5M
du1.get(ChronoUnit.SECONDS):3600
du2.get(ChronoUnit.SECONDS):300


相關用法


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