當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。