📜  Java中的 YearMonth of(int, int) 方法及示例

📅  最后修改于: 2022-05-13 01:55:04.573000             🧑  作者: Mango

Java中的 YearMonth of(int, int) 方法及示例

Java中YearMonth类的of(int year, int month)方法用于从年月中获取YearMonth的实例。
句法:

public static YearMonth of(
    int year, int month)

参数:此方法接受两个参数:

  • year :表示年份。
  • :表示一年中的月份。

返回值:此方法返回年-月

异常:如果任何字段的值无效,此方法将引发DateTimeException

下面的程序说明了Java中 YearMonth 的 of(int year, int month) 方法:

方案一:

// Java program to demonstrate
// YearMonth.of (int year, int month) method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // apply of (int year, int month) method
        // of YearMonth class
        YearMonth yearmonth = YearMonth.of(2020, 5);
  
        // print year and month
        System.out.println("YearMonth: "
                           + yearmonth);
    }
}
输出:
YearMonth: 2020-05

方案二:

// Java program to demonstrate
// YearMonth.of (int year, int month) method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // apply of (int year, int month) method
        // of YearMonth class
        YearMonth yearmonth = YearMonth.of(2020, 5);
  
        // print only year
        System.out.println("Year: "
                           + yearmonth.getYear());
    }
}
输出:
Year: 2020

方案 3:

// Java program to demonstrate
// YearMonth.of (int year, int month) method
  
import java.time.*;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // apply of (int year, int month) method
        // of YearMonth class
        YearMonth yearmonth = YearMonth.of(2020, 5);
  
        // print only month
        System.out.println("Month: "
                           + yearmonth.getMonth());
    }
}
输出:
Month: MAY

参考资料: https: Java/time/YearMonth.html#of(int, int)