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


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

Duration類withSeconds()方法

  • withSeconds() 方法可在java.time包。
  • withSeconds() 方法用於用給定的秒數表示此持續時間。
  • withSeconds() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • withSeconds() 方法在用給定的秒表示 Duration 時可能會拋出異常。
    日期時間異常:當給定的參數無效時,可能會拋出此異常。

用法:

    public Duration withSeconds(int sec_val);

參數:

  • int sec_val– 表示表示此 Duration 的秒數。

返回值:

這個方法的返回類型是Duration,它返回給定秒數的持續時間。

例:

// Java program to demonstrate the example 
// of withSeconds(int sec_val) method of Duration

import java.time.*;

public class WithSecondsfDuration {
    public static void main(String args[]) {
        // Instantiates two Duration objects
        Duration du1 = Duration.ofMinutes(2);
        Duration du2 = Duration.parse("P0DT1H0M");

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

        // represents this Duration
        // du1 with the given seconds
        Duration with_seconds = du1.withSeconds(15);

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

        // represents this Duration
        // du2 with the given seconds
        with_seconds = du2.withSeconds(30);

        // Display with_seconds
        System.out.println("du2.withSeconds(30):" + with_seconds);
    }
}

輸出

du1:PT2M
du2:PT1H
du1.withSeconds(15):PT15S
du2.withSeconds(30):PT30S


相關用法


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