Java中的 OffsetDateTime withNano() 方法及示例
Java中 OffsetDateTime 类的withNano()方法返回此 OffsetDateTime 的副本,其中纳秒更改为参数中指定的。
句法:
public OffsetDateTime withNano(int nanoOfSecond)
参数:此方法接受单个参数nanaOfSecond ,它指定要在结果中设置的纳秒,范围可以从 0 到 999、999、999..
返回值:它返回一个基于此日期的 OffsetDateTime 请求的纳秒且不为空。
异常:当纳秒值无效时,程序会抛出DateTimeException 。
下面的程序说明了withNano()方法:
方案一:
// 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
方案二:
// 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: Java/time/OffsetDateTime.html#withNano(int)