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

In this article, we will learn how to alter Year or Month or DayOfMonth fields of LocalDate using different methods provided in Java 1.8 version

Altering Day/Month/Year fields of LocalDate:

  • It is very simple to alter Day or Month or Year fields of LocalDate using below methods,
    1. withDayOfMonth() – Returns a copy of this LocalDate with the day-of-month altered
    2. withMonth() – Returns a copy of this LocalDate with the month-of-year altered
    3. withYear() – Returns a copy of this LocalDate with the year altered
  • In the below illustration, we are going to do alter operations with current LocalDate,
    1. Alter/change Day field of current LocalDate to 15 using withDayOfMonth() method
    2. Alter/change Month field of current LocalDate to 8 using withMonth() method
    3. Alter/change Year field of current LocalDate to 2023 using withYear() method
  • Finally, print LocalDate to the console

AlterLocalDate.java

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

import java.time.LocalDate;

public class AlterLocalDate {

	public static void main(String[] args) {

		// 1. get Current System Date
		LocalDate currentLocalDate = LocalDate.now();
		System.out.println("Current Date in ISO_LOCAL_DATE format is = "
				+ currentLocalDate);


		// 1.1 alter/change day part of Current System Date
		LocalDate dateAltered = currentLocalDate.withDayOfMonth(15);
		System.out.println("\n1. Day (15) altered in Current System Date is = "
				+ dateAltered);


		// 1.2 alter/change Month part of Current System Date
		LocalDate monthAltered = currentLocalDate.withMonth(8);
		System.out.println("2. Month (8) altered in Current System Date is = "
				+ monthAltered);


		// 1.3 alter/change Year part of Current System Date
		LocalDate yearAltered = currentLocalDate.withYear(2023);
		System.out.print("3. Year (2023) altered in Current System Date is = "
				+ yearAltered);
	}
}

Output:

Current Date in ISO_LOCAL_DATE format is = 2022-07-30

1. Day (15) altered in Current System Date is = 2022-07-15
2. Month (8) altered in Current System Date is = 2022-08-30
3. Year (2023) altered in Current System Date is = 2023-07-30

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to get Number of Days in a Month from LocalDate ?
Java 8 – How to subtract Year, Month and Day fields from LocalDate ?