Sunday, October 12, 2025
HomeLanguagesJavaYearMonth atDay() method in Java

YearMonth atDay() method in Java

The atDay() method of YearMonth class in Java combines the current year-month with a day-of-month passed as parameter to it to create a LocalDate.

Syntax:  

public LocalDate atDay(int dayOfMonth)

Parameter: This method accepts a single parameter dayOfMonth. It is the day-of-month to use. It can take values from 1 to 31.

Return Value: It returns a Local Date formed by the current year-month and a day of month passed as parameter to the function.

Exception: This method throws a DateTimeException, if the day of month passed in the parameter is not valid.

Below programs illustrate the atDay() method of YearMonth in Java: 

Program 1:  

Java




// Program to illustrate the atDay() method
 
import java.util.*;
import java.time.*;
 
public class GfG {
    public static void main(String[] args)
    {
 
        // Creates a YearMonth object
        YearMonth thisYearMonth = YearMonth.of(2017, 8);
 
        // Creates a local date with this
        // YearMonth object and day passed to it
        LocalDate date = thisYearMonth.atDay(31);
 
        System.out.println(date);
    }
}


Output: 

2017-08-31

 

Program 2: To illustrate Exception. The below program throws an exception as September is of 30 days and not 31 days. 

Java




// Program to illustrate the atDay() method
 
import java.util.*;
import java.time.*;
 
public class GfG {
    public static void main(String[] args)
    {
 
        // Creates a YearMonth object
        YearMonth thisYearMonth = YearMonth.of(2017, 9);
 
        try {
            // Creates a local date with this
            // YearMonth object and day passed to it
            LocalDate date = thisYearMonth.atDay(31);
 
            System.out.println(date);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output: 

java.time.DateTimeException: Invalid date 'SEPTEMBER 31'

 

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#atDay-int-
 

RELATED ARTICLES

Most Popular

Dominic
32352 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6720 POSTS0 COMMENTS
Nicole Veronica
11885 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6840 POSTS0 COMMENTS
Ted Musemwa
7105 POSTS0 COMMENTS
Thapelo Manthata
6796 POSTS0 COMMENTS
Umr Jansen
6795 POSTS0 COMMENTS