What is Duration.minusNanos() in Java?

minusNanos() is an instance method of the Duration class, which is used to subtract the specified duration in nanoseconds from the Duration object.

The minusNanos() method is defined in the Duration class. The Duration class is defined in the java.time package. To import the Duration class, check the following import statement:

import java.time.Duration;

Syntax


public Duration minusNanos(long nanosToSubtract)

Parameters

  • long nanosToSubtract: The number of nanoseconds to subtract. It can be positive or negative.

Return value

This method returns a new instance of the Duration class with the number of nanoseconds subtracted.

Code

In the below code, we subtract 100000 nanoseconds from the baseDuration object with the help of the minusNanos() method and print the new object to the console:

import java.time.Duration;
public class Main{
public static void main(String[] args) {
Duration baseDuration = Duration.ofSeconds(3);
long nanoSecondsToSubtract = 100000;
Duration newDuration = baseDuration.minusNanos(nanoSecondsToSubtract);
System.out.printf("%s - %s nanoseconds = %s", baseDuration, nanoSecondsToSubtract, newDuration);
System.out.println();
}
}

Output

The output of the code will be as follows:


PT3S - 100000 nanoseconds = PT2.9999S

Free Resources