当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java LocalTime withNano()用法及代码示例


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

用法:

public LocalTime withNano(int nano)

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


返回值:此方法基于此时间返回带有请求的nano的LocalTime实例。

异常:如果nano值无效,则此方法引发异常DateTimeException

以下示例程序旨在说明withNano()方法:

程序1:

// 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

程序2:

// 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://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#withNano(int)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 LocalTime withNano() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。