Java LocalDateTime minusHours()

In this guide, you will learn about the LocalDateTime minusHours() method in Java programming and how to use it with an example.

1. LocalDateTime minusHours() Method Overview

Definition:

The LocalDateTime.minusHours() method returns a copy of the LocalDateTime with the specified number of hours subtracted.

Syntax:

LocalDateTime minusHours(long hours)

Parameters:

- hours: The number of hours to subtract, may be negative.

Key Points:

- The LocalDateTime.minusHours() method is useful for date and time arithmetic where you want to manipulate the hour part of a LocalDateTime.

- The returned LocalDateTime instance is immutable, which means the original LocalDateTime instance remains unchanged.

- If subtracting the hours results in a date-time before the minimum date (LocalDateTime.MIN), a DateTimeException will be thrown.

- Subtracting a negative value is the same as adding the absolute value of that number of hours.

2. LocalDateTime minusHours() Method Example

import java.time.LocalDateTime;

public class LocalDateTimeMinusHoursExample {
    public static void main(String[] args) {
        LocalDateTime dateTime = LocalDateTime.of(2023, 1, 1, 0, 0);

        // Subtract 1 hour from the LocalDateTime
        LocalDateTime result1 = dateTime.minusHours(1);

        // Add 3 hours by subtracting a negative value
        LocalDateTime result2 = dateTime.minusHours(-3);

        System.out.println("Original DateTime: " + dateTime);
        System.out.println("After subtracting 1 hour: " + result1);
        System.out.println("After adding 3 hours: " + result2);
    }
}

Output:

Original DateTime: 2023-01-01T00:00
After subtracting 1 hour: 2022-12-31T23:00
After adding 3 hours: 2023-01-01T03:00

Explanation:

In the example, we have a LocalDateTime set to January 1, 2023, at midnight (00:00).

- When we subtract 1 hour using minusHours(1), the time becomes 23:00 on December 31, 2022, demonstrating the method's capability to handle day, month, and year boundaries.

- When we add 3 hours using minusHours(-3), the time becomes 03:00 on January 1, 2023.

Comments