Home »
Java »
Java Reference »
Java LocalDate Class
Java LocalDate Class | withMonth() Method with Example
LocalDate Class withMonth() method: Here, we are going to learn about the withMonth() method of LocalDate Class with its syntax and example.
Submitted by Preeti Jain, on June 02, 2020
LocalDate Class withMonth() method
- withMonth() method is available in java.time package.
- withMonth() method is used to update this LocalDate object with the given month.
- withMonth() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- withMonth() method may throw an exception at the time of representing LocalDate with the given month.
DateTimeException: This exception may throw when the given parameter is not valid.
Syntax:
public LocalDate withMonth(int mon_val);
Parameter(s):
- int mon_val – represents months to represent this LocalDate from [1 to 12].
Return value:
The return type of this method is LocalDate, it returns the LocalDate that holds the value updated the given month in this object.
Example:
// Java program to demonstrate the example
// of withMonth(int mon_val) method of LocalDate
import java.time.*;
public class WithMonthOfLocalDate {
public static void main(String args[]) {
int month_of_year = 5;
// Instantiates two LocalDate
LocalDate l_da1 = LocalDate.parse("2007-04-04");
LocalDate l_da2 = LocalDate.of(2008, Month.FEBRUARY, 06);
// Display l_da1,l_da2
System.out.println("LocalDate l_da1,l_da2 : ");
System.out.println("l_da1: " + l_da1);
System.out.println("l_da2: " + l_da2);
System.out.println("month_of_year to update: " + month_of_year);
System.out.println();
// Here, this method updates month-of-year
// with the given value in this LocalDate
// l_da1
LocalDate l_date = l_da1.withMonth(month_of_year);
// Display l_date
System.out.println("l_da1.withMonth(month_of_year): " + l_date);
// Here, this method updates month-of-year
// with the given month-of-year in this
// LocalDate l_da2
l_date = l_da2.withMonth(month_of_year);
// Display l_date
System.out.println("l_da2.withMonth(month_of_year): " + l_date);
}
}
Output
LocalDate l_da1,l_da2 :
l_da1: 2007-04-04
l_da2: 2008-02-06
month_of_year to update: 5
l_da1.withMonth(month_of_year): 2007-05-04
l_da2.withMonth(month_of_year): 2008-05-06