Java LocalDate withYear() Method

Java withYear() method is used to get a date with the specified new year. It returns a copy of this LocalDate with the year altered. For example, we have a date 2015-01-14 then setting year as 2010 will result in 2010-01-14.

If the day-of-month is invalid for the year, it will be changed to the last valid day of the month.

It takes an argument of int type. The syntax of the method is given.

Syntax

public LocalDate withYear(int year)

Parameters:

year - the year to set in the result.

Returns:

Returns LocalDate based on this date with the requested year.

Time for an Example:

Let's take an example to create a new date by setting a new value of a year. Here, we are using withYear() method to set a new year for the date.

import java.time.LocalDate;
public class DateDemo {
	
	public static void main(String[] args){  
		
		LocalDate localDate = LocalDate.of(2002, 01, 10);
		System.out.println(localDate);
		localDate = localDate.withYear(2011);
		System.out.println("New Date : "+localDate);
	}
}


2002-01-10
New Date : 2011-01-10

Time for another Example:

Let's take another example to understand the withYear() method. Here, we are setting year as 20 and getting a new date.

import java.time.LocalDate;
public class DateDemo {
	
	public static void main(String[] args){  
		
		LocalDate localDate = LocalDate.of(2002, 01, 10);
		System.out.println(localDate);
		localDate = localDate.withYear(20);
		System.out.println("New Date : "+localDate);
	}
}


2002-01-10
New Date : 0020-01-10

Live Example:

Try with a live example, execute the code instantly with our powerful Online Java Compiler.