📌  相关文章
📜  Java中的 OffsetDateTime plusNanos() 方法及示例

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

Java中的 OffsetDateTime plusNanos() 方法及示例

Java中 OffsetDateTime 类的plusNanos()方法返回此 OffsetDateTime 的副本,其中指定的纳秒数添加到解析的日期和时间。

句法:

public OffsetDateTime plusNanos(long nanoseconds)

参数:此方法接受单个参数nanoseconds ,它指定要添加到解析日期的纳秒。它也可以是负数,在这种情况下,它会减去纳秒数。

返回值:它基于此日期时间返回一个 OffsetDateTime,添加纳秒且不为空。

异常:程序在超出支持的数据和时间范围时抛出DateTimeException

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

方案一:

// Java program to demonstrate the plusNanos() method
  
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
  
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);
  
        // Subtracts the number of nanoseconds
        System.out.println("Date1 after adding nanoseconds: "
                           + date1.plusNanos(-120));
    }
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date1 after adding nanoseconds: 2018-12-12T13:30:29.999999880+05:00

方案二:

// Java program to demonstrate the plusNanos() method
  
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
  
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);
  
        // Subtracts the number of nanoseconds
        System.out.println("Date1 after adding nanoseconds: "
                           + date1.plusNanos(140));
    }
}
输出:
Date1: 2018-12-12T13:30:30+05:00
Date1 after adding nanoseconds: 2018-12-12T13:30:30.000000140+05:00

参考:https: Java/time/OffsetDateTime.html#plusNanos(long)