Sunday, November 23, 2025
HomeLanguagesJavaLocalDate withDayOfMonth() method in Java with Examples

LocalDate withDayOfMonth() method in Java with Examples

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

Syntax:

public LocalDate withDayOfMonth(int dayOfMonth)

Parameter: This method accepts a mandatory parameter dayOfMonth whicthe day-of-month to set in the result, from 1 to 28-31.

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

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

Below programs illustrate the LocalDate.withDayOfMonth() method:

Program 1:




// Program to illustrate the withDayOfMonth() 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.withDayOfMonth(01);
  
        // Prints the date with year
        System.out.println("The date with day of the month is: " + result);
    }
}


Output:

The date with day of the month is: 2018-12-01

Program 2:




// Program to illustrate the withDayOfMonth() 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.withDayOfMonth(35);
  
            // Prints the date with year
            System.out.println("The date with day of the month is: " + result);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output:

java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 35

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

RELATED ARTICLES

Most Popular

Dominic
32409 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6908 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6865 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS