Java 中的 `LocalDateTime` 的 `withNano()` 方法


Java 中 `LocalDateTime` 類中的 `withNano()` 方法用於建立 `LocalDateTime` 的一個不可變副本,並根據需要更改其納秒。此方法需要一個引數,即要設定在 `LocalDateTime` 中的納秒,並返回納秒已按需要更改的 `LocalDateTime`。

以下是一個演示此方法的程式 −

示例

 即時演示

import java.time.*;
public class Main {
   public static void main(String[] args) {
      LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
      System.out.println("The LocalDateTime is: " + ldt1);
      LocalDateTime ldt2 = ldt1.withNano(5);
      System.out.println("The LocalDateTime with nanosecond altered is: " + ldt2);
   }
}

輸出

The LocalDateTime is: 2019-02-18T23:15:30
The LocalDateTime with nanosecond altered is: 2019-02-18T23:15:30.000000005

現在,讓我們瞭解一下上述程式。

首先顯示 `LocalDateTime`。然後使用 `withNano()` 方法顯示納秒更改為 5 的 `LocalDateTime`。演示此方法的程式碼片段如下 −

LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
System.out.println("The LocalDateTime is: " + ldt1);
LocalDateTime ldt2 = ldt1.withNano(5);
System.out.println("The LocalDateTime with nanosecond altered is: " + ldt2);

更新於:2019-7-30

166 次瀏覽

開啟您的 職業

透過完成課程獲得認證

入門
廣告