Friday, May 22, 2026
HomeLanguagesJavaLocalDate withMonth() method in Java with Examples

LocalDate withMonth() method in Java with Examples

The withMonth() method of LocalDate class in Java returns a copy of this LocalDate with the month-of-year altered.

Syntax:

public LocalDate withMonth(int month)

Parameter: This method accepts a mandatory parameter month which specifies the month-of-year to set in the result, from 1 i.e., January to 12 i.e., December.

Returns: The function returns a LocalDate based on this date with the requested month, not null.

Exceptions: The function throws a DateTimeException when the month-of-year value is invalid.

Below programs illustrate the LocalDate.withMonth() method:

Program 1:




// Program to illustrate the withMonth() method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
  
        // Parses the date
        LocalDate dt1 = LocalDate.parse("2018-12-07");
        LocalDate result = dt1.withMonth(01);
  
        // Prints the date with year
        System.out.println("The date with month is: " + result);
    }
}


Output:

The date with month is: 2018-01-07

Program 2:




// Program to illustrate the withMonth() method
// Exceptions
import java.util.*;
import java.time.*;
import java.time.temporal.ChronoField;
  
public class GfG {
    public static void main(String[] args)
    {
  
        try {
            // Parses the date
            LocalDate dt1 = LocalDate.parse("2018-12-07");
            LocalDate result = dt1.withMonth(13);
  
            // Prints the date with year
            System.out.println("The date with month is: " + result);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output:

java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 13

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#withMonth(int)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS