Java中的LocalDateTime withNano()方法

使用withNano()Java中LocalDateTime类中的方法,可以完成对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。然后使用方法显示将纳秒更改为5的LocalDateTime withNano()。演示这的代码片段如下-

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);