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 次浏览

开启您的 职业

通过完成课程获得认证

入门
广告
© . All rights reserved.