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


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


Java中OffsetDateTime类的withNano()方法返回此OffsetDateTime的副本,该副本具有按参数指定更改的纳秒级。

用法:

public OffsetDateTime withNano(int nanoOfSecond)

参数:此方法接受单个参数nanaOfSecond,该参数指定要在结果中设置的纳秒,范围可以从0到999、999、999。


返回值:它基于此日期返回一个OffsetDateTime,并带有请求的纳秒级且不为null。

异常:纳秒值无效时,程序将引发DateTimeException。

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

程序1:

// Java program to demonstrate the withNano() method 
  
import java.time.OffsetDateTime; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Parses the date1 
        OffsetDateTime date1 
            = OffsetDateTime 
                  .parse( 
                      "2018-12-12T13:30:30+05:00"); 
  
        // Prints dates 
        System.out.println("Date1: " + date1); 
  
        // Changes the nano-of-second 
        System.out.println("Date1 after altering nano-of-second: "
                           + date1.withNano(1000)); 
    } 
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date1 after altering nano-of-second: 2018-12-12T13:30:30.000001+05:00

程序2:

// Java program to demonstrate the withNano() method 
  
import java.time.OffsetDateTime; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        try { 
  
            // Parses the date1 
            OffsetDateTime date1 
                = OffsetDateTime 
                      .parse( 
                          "2018-12-12T13:30:30+05:00"); 
  
            // Prints dates 
            System.out.println("Date1: " + date1); 
  
            // Changes the nano-of-second 
            System.out.println("Date1 after altering nano-of-second: "
                               + date1.withNano(1000000000)); 
        } 
        catch (Exception e) { 
            System.out.println("Exception: " + e); 
        } 
    } 
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Exception: java.time.DateTimeException: 
           Invalid value for NanoOfSecond (valid values 0 - 999999999): 1000000000

参考: https://docs.oracle.com/javase/10/docs/api/java/time/OffsetDateTime.html#withNano(int)



相关用法


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