The minusDays() method of the LocalDate class is used to subtract a specified number of days from a given date and return a new LocalDate instance. Since LocalDate is immutable, the original date object remains unchanged after the operation. DateTimeException is thrown if the resulting date exceeds the supported date range of LocalDate.
Example:
import java.time.LocalDate;
class GFG {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("2023-01-10");
LocalDate updatedDate = date.minusDays(5);
System.out.println(updatedDate);
}
}
Output
2023-01-05
Explanation:
- LocalDate.parse("2023-01-10") creates the initial date stored in date.
- date.minusDays(5) subtracts 5 days and returns a new LocalDate, which is stored in updatedDate.
Syntax
public LocalDate minusDays(long daysToSubtract)
- Parameters: daysToSubtract: the number of days to subtract from the current date. A negative value adds days instead of subtracting.
- Return value: This method returns a LocalDate based on this date with the days subtracted, not null.
Program 1. Subtracting Positive Days
Subtracting a positive value using minusDays() results in a date that is earlier than the original LocalDate.
import java.time.LocalDate;
public class GFG {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("2018-11-13");
System.out.println("Before subtracting days: " + date);
LocalDate returnValue = date.minusDays(17);
System.out.println("After subtracting days: " + returnValue);
}
}
Output
Before subtracting days: 2018-11-13 After subtracting days: 2018-10-27
Explanation:
- date holds the initial value 2018-11-13.
- Calling date.minusDays(17) subtracts 17 days from the original date.
- The result is stored in returnValue, which represents 2018-10-27.
- The original date variable is not modified.
Program 2. Passing a Negative Value to minusDays()
Providing a negative value to minusDays() increases the date value, effectively moving it forward in time.
import java.time.LocalDate;
public class GFG {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("2018-12-24");
System.out.println("Before subtracting days: " + date);
LocalDate returnValue = date.minusDays(-15);
System.out.println("After subtracting days: " + returnValue);
}
}
Output
Before subtracting days: 2018-12-24 After subtracting days: 2019-01-08
Explanation:
- initial LocalDate object represents 2018-12-24.
- minusDays(-15) adds 15 days because the value passed is negative.
- returned date 2019-01-08 is stored in returnValue.
- this confirms that minusDays() supports negative input values.