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)
相關用法
- Java LocalDateTime withNano()用法及代碼示例
- Java LocalTime withNano()用法及代碼示例
- Java ZonedDateTime withNano()用法及代碼示例
- Java OffsetDateTime from()用法及代碼示例
- Java OffsetDateTime get()用法及代碼示例
- Java OffsetDateTime until()用法及代碼示例
- Java OffsetDateTime with()用法及代碼示例
- Java OffsetDateTime withMinute()用法及代碼示例
- Java OffsetDateTime range()用法及代碼示例
- Java OffsetDateTime format()用法及代碼示例
- Java OffsetDateTime getDayOfYear()用法及代碼示例
- Java OffsetDateTime getLong()用法及代碼示例
- Java OffsetDateTime getHour()用法及代碼示例
- Java OffsetDateTime getDayOfWeek()用法及代碼示例
- Java OffsetDateTime getMonth()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 OffsetDateTime withNano() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。