Java LocalDate minusDays()

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

1. LocalDate minusDays() Method Overview

Definition:

The minusDays() method of the LocalDate class in Java is used to return a copy of this LocalDate with the specified number of days subtracted. This method is useful for performing date arithmetic, especially when calculating past dates from a given date.

Syntax:

public LocalDate minusDays(long daysToSubtract)

Parameters:

- daysToSubtract: the days to subtract, may be negative

Key Points:

- The minusDays() method is used for subtracting days from the current LocalDate instance and returns a new LocalDate object.

- If the parameter is negative, it effectively adds the days to the date.

- The returned LocalDate is immutable, ensuring thread safety.

- The LocalDate class is part of the java.time package, introduced in Java 8.

- If the new date exceeds the maximum or minimum supported value of LocalDate, a DateTimeException will be thrown.

2. LocalDate minusDays() Method Example

import java.time.LocalDate;
import java.time.Month;

public class LocalDateMinusDaysExample {
    public static void main(String[] args) {
        // Create a LocalDate object representing a specific date
        LocalDate date = LocalDate.of(2023, Month.SEPTEMBER, 20);

        // Print the original LocalDate object
        System.out.println("Original Date: " + date);

        // Subtract 5 days from the LocalDate object using the minusDays() method
        LocalDate newDate = date.minusDays(5);

        // Print the new LocalDate object
        System.out.println("New Date after subtracting 5 days: " + newDate);

        // Add 10 days to the original LocalDate object by subtracting negative days
        LocalDate futureDate = date.minusDays(-10);

        // Print the new LocalDate object after adding 10 days
        System.out.println("New Date after subtracting -10 days: " + futureDate);
    }
}

Output:

Original Date: 2023-09-20
New Date after subtracting 5 days: 2023-09-15
New Date after subtracting -10 days: 2023-09-30

Explanation:

In this example, we first create a LocalDate object representing the date 20th September 2023. We then subtract 5 days from this date using the minusDays() method and print the result, which is 15th September 2023. Additionally, we add 10 days to the original date by subtracting a negative value and print the result, which is 30th September 2023.

Comments