Instant plusNanos() method in Java

Java 8Object Oriented ProgrammingProgramming

An immutable copy of a instant where some nanoseconds are added to it can be obtained using the plusNanos() method in the Instant class in Java. This method requires a single parameter i.e. the number of nanoseconds to be added and it returns the instant with the added nanoseconds.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.*;
public class Demo {
   public static void main(String[] args) {
      Instant i = Instant.now();
      System.out.println("The current instant is: " + i);
      System.out.println("An instant with 1000000000 nanoseconds added is: " + i.plusNanos(1000000000));
   }
}

Output

The current instant is: 2019-02-12T12:26:03.868Z
An instant with 1000000000 nanoseconds added is: 2019-02-12T12:26:04.868Z

Now let us understand the above program.

First the current instant is displayed. Then an immutable copy of the instant where 1000000000 nanoseconds are added is obtained using the plusNanos() method and this is displayed. A code snippet that demonstrates this is as follows −

Instant i = Instant.now();
System.out.println("The current instant is: " + i);
System.out.println("An instant with 1000000000 nanoseconds added is: " + i.plusNanos(1000000000));
raja
Published on 28-Mar-2019 05:36:42

Advertisements