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


Java YearMonth get()用法及代碼示例

Java中的YearMonth類的get()方法用於從此year-month中獲取整數形式的指定字段的值。此方法在year-month中查詢指定字段的值。返回的值將始終在有效範圍內。如果由於不支持該字段或出於某些其他原因而無法返回該值,則會引發異常。

用法:

public int get(TemporalField field)

參數:此方法接受field作為參數,代表需要其值的TemporalField。



返回值:此方法返回該字段的值。

異常:該方法引發以下異常:

  • DateTimeException-如果無法獲取該字段的值,或者該值超出該字段的有效值範圍。
  • UnsupportedTemporalTypeException-如果不支持該字段或值的範圍超過int。
  • ArithmeticException-如果發生數字溢出。

以下示例程序旨在說明Java中YearMonth的get()方法:

程序1:

// Java program to demonstrate 
// YearMonth.get() method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create YearMonth object 
        YearMonth yearmonth 
            = YearMonth.of(2020, 5); 
  
        // apply get() method of 
        // YearMonth class to get year 
        // It will store year 
        // in variable of type int 
        int year 
            = yearmonth.get( 
                ChronoField.YEAR_OF_ERA); 
  
        // print year 
        System.out.println("YEAR:" + year); 
    } 
}
輸出:
YEAR:2020

程序2:

// Java program to demonstrate 
// YearMonth.get() method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create YearMonth object 
        YearMonth yearmonth 
            = YearMonth.of(2020, 5); 
  
        // apply get() method of 
        // YearMonth class to get month 
        // It will store month 
        // in variable of type int 
        int month 
            = yearmonth.get( 
                ChronoField.MONTH_OF_YEAR); 
  
        // print month 
        System.out.println("MONTH:" + month); 
    } 
}
輸出:
MONTH:5

參考文獻: https://docs.oracle.com/javase/10/docs/api/java/time/YearMonth.html#get(java.time.temporal.TemporalField)




相關用法


注:本文由純淨天空篩選整理自pp_pankaj大神的英文原創作品 YearMonth get() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。