Java Instant Class | plusNanos() Method with Example

Instant Class plusNanos() method: Here, we are going to learn about the plusNanos() method of Instant Class with its syntax and example.
Submitted by Preeti Jain, on May 26, 2020

Instant Class plusNanos() method

  • plusNanos() method is available in java.time package.
  • plusNanos() method is used to add the given duration in nanoseconds to this Instant and return the Instant.
  • plusNanos() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • plusNanos() method may throw an exception at the time of performing addition.
    DateTimeException: This exception may throw when this Instant value reaches out of the min or max instant.

Syntax:

    public Instant plusNanos(long nanos_val);

Parameter(s):

  • long nanos_val – represents the nanoseconds value to add to this Instant.

Return value:

The return type of this method is Instant, it returns the Instant that holds the value added the given nanoseconds to this Instant.

Example:

// Java program to demonstrate the example 
// of plusNanos(long nanos_val) method 
// of Instant

import java.time.*;

public class PlusNanosOfInstant {
    public static void main(String args[]) {
        long nanos = 20000;

        // Instantiates two Instant
        Instant ins1 = Instant.parse("2006-04-03T05:10:15.60Z");
        Instant ins2 = Instant.now();

        // Display ins1, ins2 and nanos
        System.out.println("Instant ins1 and ins2: ");
        System.out.println("ins1: " + ins1);
        System.out.println("ins2: " + ins2);
        System.out.println("nanos to add: " + nanos);

        System.out.println();

        // Here, this method adds the given duration
        // in nanoseconds with this Instant ins1 
        // i.e. here we are adding the given 20000 
        // nanoseconds with this ins1 

        Instant plus_nanos = ins1.plusNanos(nanos);

        // Display plus_nanos
        System.out.println("ins1.plusNanos(nanos): " + plus_nanos);

        // Here, this method adds the given duration
        // in nanoseconds with this Instant ins2 
        // and returns the Instant i.e. here we 
        // are adding the given 20000 nanoseconds
        // with this ins2 

        plus_nanos = ins2.plusNanos(nanos);

        // Display plus_nanos
        System.out.println("ins2.plusNanos(nanos): " + plus_nanos);
    }
}

Output

Instant ins1 and ins2: 
ins1: 2006-04-03T05:10:15.600Z
ins2: 2020-05-27T00:16:53.007772Z
nanos to add: 20000

ins1.plusNanos(nanos): 2006-04-03T05:10:15.600020Z
ins2.plusNanos(nanos): 2020-05-27T00:16:53.007792Z


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.