当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java YearMonth of(int, int)用法及代码示例


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

public static YearMonth of(
    int year, int month)

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

  • year:代表年份。
  • month:代表一年中的月份。

返回值:此方法返回year-month。



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

以下示例程序旨在说明Java中YearMonth的of(int year,int month)方法:

程序1:

// 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

程序2:

// 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://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#of(int, int)




相关用法


注:本文由纯净天空筛选整理自pp_pankaj大神的英文原创作品 YearMonth of(int, int) method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。