Java month of()方法

来源:这里教程网 时间:2026-02-17 20:57:45 作者:

Java month of()方法

of() 方法是Month ENUM的一个内置方法,用于从一个整数值生成一个Month实例。整数值应该在1-12的范围内,代表12个月中的任何一个月,该方法从它生成一个Month实例,代表一年中的某个月份。

语法:

public static Month of(int month)

参数 :该方法接受一个单一的参数month,它是整数类型。

返回值 :该方法返回使用所传递的参数生成的相应的月份实例。

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

下面的程序说明了上述方法。

程序1 :

import java.time.*;import java.time.Month;import java.time.temporal.ChronoField;  class monthEnum {    public static void main(String[] args)    {        // Create a month instance        Month month = Month.of(2);          // Print the month Instance        System.out.println(month);    }}

输出。

FEBRUARY

程序2 :

import java.time.*;import java.time.Month;import java.time.temporal.ChronoField;  class monthEnum {    public static void main(String[] args)    {        // Create a month instance        Month month = Month.of(12);          // Print the month Instance        System.out.println(month);    }}

输出。

DECEMBER

参考资料 : https://docs.oracle.com/javase/8/docs/api/java/time/Month.html#of-int-

相关推荐