Duration minusMinutes(long) method in Java with Examples
The minusMinutes(long minutes) method in the java.time.Duration class is used to create a copy of the current Duration object with the specified number of minutes subtracted from it. The Duration class represents a time-based amount of time, such as '34.5 seconds'. The minusMinutes(long minutes) method is useful for manipulating durations and performing time calculations.
Declaration
public Duration minusMinutes(long minutes)
Parameters
minutes: The number of minutes to subtract from the duration. It is of type long.
Returns
It returns a Duration object that is a copy of the original duration with the specified number of minutes subtracted.
Usage Example
Let's explore the usage of the minusMinutes(long minutes) method with an example,
FileName: LocalDateTimeMinusMinutesExample.java
import java.time.Duration; public class LocalDateTimeMinusMinutesExample { public static void main(String[] args) { // Creating a Duration of 2 hours Duration duration = Duration.ofHours(2); System.out.println("Original Duration: " + duration); // Subtracting 30 minutes from the Duration Duration updatedDuration = duration.minusMinutes(30); System.out.println("Updated Duration: " + updatedDuration); } }
Output:
Original Duration: PT2H Updated Duration: PT1H30M
Benefits
Immutability: The Duration class is immutable, meaning the original duration instance remains unchanged, and a new instance is returned with the updated value. It helps in writing thread-safe code.
Precision: The Duration class provides nanosecond precision, which is suitable for high-precision time calculations.
Readability: Using methods like minusMinutes() makes the code more readable and self-explanatory, enhancing maintainability.
Conclusion
The minusMinutes(long minutes) method in the Duration class is a useful tool for manipulating durations in Java. By providing an easy and intuitive way to subtract minutes from a duration, it enhances code readability and maintainability. Its immutable nature ensures that our code remains thread-safe and avoids unintended side-effects. Overall, this method is a valuable part of the java.time package for handling time-based calculations efficiently.