LocalDateTime plusNanos() method in Java with Examples

The plusNanos() method of LocalDateTime class is used to return a copy of this date-time with the specified nanoSeconds added.
Syntax:
public LocalDateTime plusNanos(long nanoSeconds)
Parameter: It accepts a single parameter nanoSeconds which specifies the nanoSeconds to add which may be negative.
Return Value: This method returns a LocalDateTime based on this date-time with the nanoSeconds added.
Exceptions: The program throws a DateTimeException which is thrown if the result exceeds the supported nanoSeconds range.
Below programs illustrate the LocalDateTime.plusNanos() method in Java:
Program 1:
Java
// Program to illustrate the plusNanos() methodimport java.util.*;import java.time.*;public class GfG { public static void main(String[] args) { LocalDateTime dt1 = LocalDateTime .parse("2018-01-11T10:15:30"); System.out.println("LocalDateTime with 10000 nanoSeconds added: " + dt1.plusNanos(10000)); }} |
Output:
LocalDateTime with 10000 nanoSeconds added: 2018-01-11T10:15:30.000010
LocalDateTime with 10000 nanoSeconds added: 2018-01-11T10:15:30.000010
Program 2:
Java
// Program to illustrate the plusNanos() methodimport java.util.*;import java.time.*;public class GfG { public static void main(String[] args) { LocalDateTime dt1 = LocalDateTime .parse("2018-01-11T08:15:30"); System.out.println("LocalDateTime with -1500 nanoSeconds added: " + dt1.plusNanos(-1500)); }} |
Output:
LocalDateTime with -1500 nanoSeconds added: 2018-01-11T08:15:29.999998500
LocalDateTime with -1500 nanoSeconds added: 2018-01-11T08:15:29.999998500
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDateTime.html#plusNanos(long)



