Java year atMonth(int)方法

来源:这里教程网 时间:2026-02-17 21:17:55 作者:

Java year atMonth(int)方法

Java中Year类的atMonth(int)方法将当前年份对象与作为参数传递的月份结合起来,以创建一个YearMonth对象。

语法:

public YearMonth atMonth(int month)

参数 :该方法接受一个单一的参数month。它是要使用的年月日。它需要一个介于1和12之间的整数,不能为空。

返回值 : 它返回一个由当前年份对象和作为参数传递给函数的有效月份组成的YearMonth对象。

异常 :如果传递给它的参数中的月份无效,该方法会抛出一个 DateTimeException

下面的程序说明了Java中year的atMonth(int)方法:
程序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);    }}

输出:

2017-04

节目2 :为了说明例外情况。

// 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);        }    }}

输出:

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

参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/Year.html#atMonth-

相关推荐