📜  Java中的 LocalTime withNano() 方法及示例

📅  最后修改于: 2022-05-13 01:54:54.268000             🧑  作者: Mango

Java中的 LocalTime withNano() 方法及示例

LocalTime类的withNano()方法用于获取此 LocalTime 的副本,其中 nanos 更改为作为参数传递给此方法的 nanos。此 LocalTime 的其余值将保持不变。此实例是不可变的,不受此方法调用的影响。

句法:

public LocalTime withNano(int nano)

参数:此方法接受单个参数nano ,它表示要在结果中设置的纳秒,从 0 到 999、999、999。

返回值:此方法根据请求的 nano 返回一个LocalTime 实例

异常:如果 nano 值无效,此方法会抛出异常DateTimeException

下面的程序说明了 withNano() 方法:

方案一:

// Java program to demonstrate
// LocalTime.withNano() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a LocalTime object
        LocalTime time
            = LocalTime.parse("19:34:50.63");
  
        // print time
        System.out.println("Old LocalTime: "
                           + time);
  
        // Get a new LocalDateTime with nanos 100000
        LocalTime newtime = time.withNano(100000);
  
        // print result
        System.out.println("New LocalDateTime: "
                           + newtime);
    }
}
输出:
Old LocalTime: 19:34:50.630
New LocalDateTime: 19:34:50.000100

方案二:

// Java program to demonstrate
// LocalTime.withNano() method
  
import java.time.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a LocalTime object
        LocalTime time
            = LocalTime.parse("01:21:30.13");
  
        // print time
        System.out.println("Old LocalTime: "
                           + time);
  
        // Get a new LocalDateTime with nanos 999999
        LocalTime newtime = time.withNano(999999);
  
        // print result
        System.out.println("New LocalDateTime: "
                           + newtime);
    }
}
输出:
Old LocalTime: 01:21:30.130
New LocalDateTime: 01:21:30.000999999

参考资料: https: Java/time/LocalTime.html#withNano(int)