What is Duration.minusMillis() in Java?

minusMillis() is an instance method of the Duration class that is used to subtract the specified duration in milliseconds from the Duration object.

The minusMillis() method is defined in the Duration class. The Duration class is defined in the java.time package. To import the Duration class, use the following import statement.

import java.time.Duration;

Syntax


public Duration minusMillis(long millisToSubtract)

Parameters

  • long millisToSubtract: This is the number of milliseconds to subtract. This parameter can be positive or negative.

Return value

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

Code

In the code below, we subtract 1000 milliseconds from the baseDuration object with the help of the minusMillis() 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);
int milliSecondsToSubtract = 1000;
Duration newDuration = baseDuration.minusMillis(milliSecondsToSubtract);
System.out.printf("%s - %s milliseconds = %s", baseDuration, milliSecondsToSubtract, newDuration);
}
}

Note: The output is given in the ISO 8601 format.

  • P represents a duration
  • T represents time
  • S represents seconds

Free Resources