Java 8 – How to subtract Year, Month and Day fields from LocalDate ?

In this article, we will learn how to subtract Year or Month or DayOfMonth fields from LocalDate

Subtracting Day/Week/Month/Year from LocalDate:

  • It is very simple to subtract Day or Week or Month or Year fields from LocalDate using below methods,
    1. minusDays() – Returns a copy of invoking LocalDate with the specified number of days subtracted
    2. minusWeeks() – Returns a copy of invoking LocalDate with the specified number of weeks subtracted
    3. minusMonths() – Returns a copy of invoking LocalDate with the specified number of months subtracted
    4. minusYears() – Returns a copy of invoking LocalDate with the specified number of years subtracted
  • In the below illustration, we are going to do below operations with current LocalDate,
    1. Subtract 5 Days from LocalDate using minusDays() method
    2. Subtract 2 Weeks from LocalDate using minusWeeks() method
    3. Subtract 3 Months from LocalDate using minusMonths() method
    4. Subtract 1 Year from LocalDate using minusYears() method
  • Finally, print LocalDate to the console

SubtractFromLocalDate.java

package in.bench.resources.java8.localdate.examples;

import java.time.LocalDate;

public class SubtractFromLocalDate {

	public static void main(String[] args) {

		// 1. get current system date
		LocalDate localDate = LocalDate.now();
		System.out.println("Current System Date is :- " + localDate);


		// 1.1 subtract 5 days from current system date
		LocalDate subtract_5_Days = localDate.minusDays(5);
		System.out.println("\n1. After subtracting 5 Days from Current System Date is :- "
				+ subtract_5_Days);


		// 1.2 subtract 2 weeks from current system date
		LocalDate subtract_2_Weeks = localDate.minusWeeks(2);
		System.out.println("2. After subtracting 2 Weeks from Current System Date is :- "
				+ subtract_2_Weeks);


		// 1.3 subtract 3 months from current system date
		LocalDate subtract_3_Months = localDate.minusMonths(3);
		System.out.println("3. After subtracting 3 Months from Current System Date is :- "
				+ subtract_3_Months);


		// 1.4 subtract 1 year from current system date
		LocalDate subtract_1_Year = localDate.minusYears(1);
		System.out.print("4. After subtracting 1 Year from Current System Date is :- "
				+ subtract_1_Year);
	}
}

Output:

Current System Date is :- 2022-07-30

1. After subtracting 5 Days from Current System Date is :- 2022-07-25
2. After subtracting 2 Weeks from Current System Date is :- 2022-07-16
3. After subtracting 3 Months from Current System Date is :- 2022-04-30
4. After subtracting 1 Year from Current System Date is :- 2021-07-30

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to alter Year, Month and Day fields of LocalDate ?
Java 8 – How to add Year, Month and Day fields to LocalDate ?