Friday, October 17, 2025
HomeLanguagesJavaYear atMonth(int) method in Java

Year atMonth(int) method in Java

The atMonth(int) method of Year class in Java combines the current year object with a month passed as parameter to it to create a YearMonth object.

Syntax:

public YearMonth atMonth(int month)

Parameter: This method accepts a single parameter month. It is the month-of-year to use. It takes an integer value between 1 and 12 and cannot be NULL.

Return Value: It returns a YearMonth object formed by the current year object and a valid month passed as parameter to the function.

Exception: This method throws a DateTimeException, if the month passed to it as parameter is invalid.

Below programs illustrate the atMonth(int) method of Year in Java:
Program 1:




// Program to illustrate the atMonth(int) method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
        // Creates a Year object
        Year thisYear = Year.of(2017);
  
        // Creates a YearMonth with this
        // Year object and Month passed to it
        YearMonth yearMonth = thisYear.atMonth(4);
  
        System.out.println(yearMonth);
    }
}


Output:

2017-04

Program 2: To illustrate Exception.




// Program to illustrate the atMonth(int) method
  
import java.util.*;
import java.time.*;
  
public class GfG {
    public static void main(String[] args)
    {
        // Creates a Year object
        Year thisYear = Year.of(2018);
  
        try {
            // Creates a YearMonth with this
            // Year object and Month passed to it
            YearMonth yearMonth = thisYear.atMonth(16);
  
            System.out.println(yearMonth);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output:

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

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#atMonth-

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

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS