LAST UPDATED: NOVEMBER 27, 2020
Java LocalDate withMonth() Method
Java withMonth() method is used to get a date with the new month-of-year. It returns a copy of this LocalDate
with the month altered. For example, we have a date 2015-01-14 then setting month-of-year as 10 will result in 2015-10-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 withMonth(int month)
Parameters:
month - the month-of-year to set in the result.
Returns:
Returns LocalDate based on this date with the requested month.
Time for an Example:
Let's take an example to create a new date by setting a new value of a month-of-year. Here, we are using withMonth()
method to set a new month 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.withMonth(10);
System.out.println("New Date : "+localDate);
}
}
2002-01-10
New Date : 2002-10-10
Time for another Example:
Let's take another example to understand the withMonth()
method. Here, we are setting month-of-year as 12 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.withMonth(12);
System.out.println("New Date : "+localDate);
}
}
2002-01-10
New Date : 2002-12-10
Live Example:
Try with a live example, execute the code instantly with our powerful Online Java Compiler.