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


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

Duration類from()方法

  • from() 方法可在java.time包。
  • from() 方法用於從給定的 TemporalAmount 返回此 Duration 的副本。
  • from() 方法是一個靜態方法,它可以通過類名訪問,如果我們嘗試使用類對象訪問該方法,那麽我們不會得到錯誤。
  • from() 方法在從給定數量返回 Duration 時可能會拋出異常。
    • 日期時間異常:當給定的 amt 無法轉換為 Duration 時,可能會拋出此異常。
    • 算術異常:當計算超過限製時可能會拋出此異常。

用法:

    public static Duration from(TemporalAmount amt);

參數:

  • TemporalAmount amt– 表示要轉換為 Duration 的數量。

返回值:

這個方法的返回類型是Duration,它返回根據給定數量計算的持續時間。

例:

// Java program to demonstrate the example 
// of Duration from(TemporalAmount amt) method of Duration

import java.time.*;

public class FromOfDuration {
    public static void main(String args[]) {
        // Instantiates a Duration object
        Duration du1 = Duration.ofHours(10);

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

        // returns an instance of 
        // Duration from the given temporal 
        // amount i.e. here the given amount is
        // 10 hrs so it generates a new Duration
        // (du_from) for the given amount
        Duration du_from = Duration.from(du1);

        // Display du_from
        System.out.println("du_from:" + du_from);

        // Here, we are converting 10 hrs into Minutes
        System.out.println("du_from.toMinutes():" + du_from.toMinutes());

        // Here, we are converting 10 hrs into Seconds
        System.out.println("du_from.toSeconds():" + du_from.toSeconds());
    }
}

輸出

du1:PT10H
du_from:PT10H
du_from.toMinutes():600
du_from.toSeconds():36000


相關用法


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