Home »
Java »
Java Reference »
Java Instant Class
Java Instant Class | minusNanos() Method with Example
Instant Class minusNanos() method: Here, we are going to learn about the minusNanos() method of Instant Class with its syntax and example.
Submitted by Preeti Jain, on May 26, 2020
Instant Class minusNanos() method
- minusNanos() method is available in java.time package.
- minusNanos() method is used to subtract the given duration in nanoseconds from this Instant and returns the Instant.
- minusNanos() 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.
- minusNanos() method may throw an exception at the time of performing subtraction.
ArithmeticException: This exception may throw when the calculated result value exceeds the limit.
Syntax:
public Instant minusNanos(long nanos_val);
Parameter(s):
- long nanos_val – represents the nanoseconds to be subtracted from this Instant.
Return value:
The return type of this method is Instant, it returns the Instant that holds the value subtracted the given duration in nanoseconds from this Instant.
Example:
// Java program to demonstrate the example
// of minusNanos(long nanos_val) method
// of Instant
import java.time.*;
public class MinusNanosOfInstant {
public static void main(String args[]) {
long nanos = 200000;
// 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 substract: " + nanos);
System.out.println();
// Here, this method subtracts the given duration
// in nanoseconds from this Instant ins1
// i.e. here we are substracting the given
// 200000 nanos from this ins1
Instant minus_nanos = ins1.minusNanos(nanos);
// Display minus_nanos
System.out.println("ins1.minusNanos(nanos): " + minus_nanos);
// Here, this method subtracts the given duration
// in nanoseconds from this Instant ins2
// i.e. here we are substracting the given
// 200000 nanos from this ins2
minus_nanos = ins2.minusNanos(nanos);
// Display minus_nanos
System.out.println("ins2.minusNanos(nanos): " + minus_nanos);
}
}
Output
Instant ins1 and ins2:
ins1: 2006-04-03T05:10:15.600Z
ins2: 2020-05-26T23:36:39.457119Z
nanos to substract: 200000
ins1.minusNanos(nanos): 2006-04-03T05:10:15.599800Z
ins2.minusNanos(nanos): 2020-05-26T23:36:39.456919Z