What is Duration.minusHours() in Java?

minusHours() is an instance method of the Duration class that subtracts the specified duration in hours from the Duration object.

The minusHours() 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 Duration class

import java.time.Duration;

minusHours() function


public Duration minusHours(long hoursToSubtract)

Parameters

long hoursToSubtract: The number of hours to subtract. It can be positive or negative.

Return value

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

Code

In the below code, we subtract four hours from the baseDuration object with the help of the minusHours() 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.ofHours(3);
int hoursToSubtract = 4;
Duration newDuration = baseDuration.minusHours(hoursToSubtract);
System.out.printf("%s - %s hours = %s", baseDuration, hoursToSubtract, newDuration);
System.out.println();
}
}

Free Resources