Instant minusNanos() method in Java with Examples

minusNanos() method of Instant class subtracts nanoseconds value passed as parameter from this instant and return the result as an instant object. This returned Instant is immutable.
Syntax:Â
Â
public Instant minusNanos(long nanosToSubtract)
Parameters: This method accepts one parameter nanosToSubtract which is nanoseconds to be subtracted.
Returns: This method returns Instant after subtraction of nanoseconds.
Exception: This method throws following exceptions:Â
Â
- DateTimeException: if the result exceeds the maximum or minimum instant.
- ArithmeticException: if numeric overflow occurs.
Below programs illustrate the minusNanos() method:
Program 1:Â
Â
Java
// Java program to demonstrate// Instant.minusNanos() methodÂ
import java.time.*;Â
public class GFG {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â
        // create a Instant object        Instant instant            = Instant.parse("2018-12-30T19:34:50.63Z");Â
        // current Instant        System.out.println("Initialize instant: "                           + instant);Â
        // subtract 430000000 nanoseconds        // means .43 seconds from this instant        Instant returnedValue            = instant.minusNanos(430000000);Â
        // print result        System.out.println("Returned Instant: "                           + returnedValue);    }} |
Output
Initialize instant: 2018-12-30T19:34:50.630Z Returned Instant: 2018-12-30T19:34:50.200Z
Program 2:Â
Â
Java
// Java program to demonstrate// Instant.minusNanos() methodÂ
import java.time.*;Â
public class GFG {Â Â Â Â public static void main(String[] args)Â Â Â Â {Â
        // create a Instant object        Instant instant = Instant.now();Â
        // current Instant        System.out.println("Current instant: "                           + instant);Â
        // subtract 540000000 nanoseconds        // means .564 seconds from this instant        Instant returnedValue            = instant.minusNanos(540000000);Â
        // print result        System.out.println("Returned Instant: "                           + returnedValue);    }} |
Output:Â
Current instant: 2018-11-27T06:43:58.495Z Returned Instant: 2018-11-27T06:43:57.955Z
Â
References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#minusNanos(long)
Â



