Java中的 YearMonth of(int, Month) 方法及示例
Java中YearMonth类的of(int year, Month month)方法用于从年月中获取YearMonth的实例。
句法:
public static YearMonth of(
int year, Month month)
参数:此方法接受两个参数:
- year :表示年份。
- 月:表示一年中的月份。
返回值:此方法返回年-月。
异常:如果任何字段的值无效,此方法将引发DateTimeException 。
下面的程序说明了Java中 YearMonth 的 of(int year, Month month) 方法:
方案一:
// Java program to demonstrate
// YearMonth.of(int year, Month month) method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// apply of(int year, Month month) method
// of YearMonth class
YearMonth yearmonth
= YearMonth.of(2020, Month.MAY);
// print year and month
System.out.println("YearMonth: "
+ yearmonth);
}
}
输出:
YearMonth: 2020-05
方案二:
// Java program to demonstrate
// YearMonth.of(int year, Month month) method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// apply of(int year, Month month) method
// of YearMonth class
YearMonth yearmonth
= YearMonth.of(2020, Month.MAY);
// print only year
System.out.println("Year: "
+ yearmonth.getYear());
}
}
输出:
Year: 2020
方案 3:
// Java program to demonstrate
// YearMonth.of(int year, Month month) method
import java.time.*;
import java.time.temporal.*;
public class GFG {
public static void main(String[] args)
{
// apply of(int year, Month month) method
// of YearMonth class
YearMonth yearmonth
= YearMonth.of(2020, Month.MAY);
// print only month
System.out.println("Month: "
+ yearmonth.getMonth());
}
}
输出:
Month: MAY
参考资料: https://docs.oracle.com/javase/10/docs/api/java /time/YearMonth.html#of(int, Java Java)