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
相關用法
- Java YearMonth with()用法及代碼示例
- Java YearMonth until()用法及代碼示例
- Java YearMonth now()用法及代碼示例
- Java YearMonth withMonth()用法及代碼示例
- Java YearMonth range()用法及代碼示例
- Java YearMonth minusMonths()用法及代碼示例
- Java YearMonth withYear()用法及代碼示例
- Java YearMonth now(clock)用法及代碼示例
- Java YearMonth query()用法及代碼示例
- Java YearMonth isValidDay()用法及代碼示例
- Java YearMonth plusYears()用法及代碼示例
- Java YearMonth plus(TemporalAmount)用法及代碼示例
- Java YearMonth lengthOfYear()用法及代碼示例
- Java YearMonth getLong()用法及代碼示例
- Java YearMonth isLeapYear()用法及代碼示例
注:本文由純淨天空篩選整理自pp_pankaj大神的英文原創作品 YearMonth get() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。