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


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

Duration類withNanos()方法

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

用法:

    public Duration withNanos(int nanos_val);

參數:

  • int nanos_val– 代表納秒以表示從 [0...999,999,999] 開始的持續時間。

返回值:

這個方法的返回類型是Duration,它返回此 Duration 與給定的納秒。

例:

// Java program to demonstrate the example 
// of withNanos(int nanos_val) method of Duration

import java.time.*;

public class WithNanosOfDuration {
    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 nanoseconds
        Duration with_nanos = du1.withNanos(50000);

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

        // represents this Duration
        // du2 with the given nanoseconds
        with_nanos = du2.withNanos(50000);

        // Display with_nanos
        System.out.println("du2.withNanos(50000):" + with_nanos);
    }
}

輸出

du1:PT2M
du2:PT1H
du1.withNanos(50000):PT2M0.00005S
du2.withNanos(50000):PT1H0.00005S


相關用法


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