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


Java YearMonth isSupported(TemporalUnit)用法及代碼示例


YearMonth類的isSupported(TemporalUnit)方法用於檢查YearMonth類是否支持指定的TemporalUnit。實際上,此方法檢查是否可以在YearMonth中使用傳遞的單位對指定的單位應用加法或減法運算。如果為false,則調用plus(long,TemporalUnit)和minus方法將引發異常。

ChronoUnit(Temporalunit)支持的單位是:

  • MONTHS
  • YEARS
  • DECADES
  • CENTURIES
  • MILLENNIA
  • ERAS

所有其他ChronoUnit實例將返回false。


用法:

public boolean isSupported(TemporalUnit unit)

參數:此方法僅接受一個代表要檢查的TemporalUnit的參數單元。

返回值:如果此YearMonth支持該單位,則此方法返回布爾值true,否則返回false。

以下示例程序旨在說明isSupported(TemporalUnit)方法:
程序1:

// Java program to demonstrate 
// YearMonth.isSupported(TemporalUnit) method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // Create a YearMonth object 
        YearMonth thisYearMonth = YearMonth.of(2017, 8); 
  
        // print instance 
        System.out.println("YearMonth:"
                           + thisYearMonth); 
  
        // apply isSupported() method 
        boolean value 
            = thisYearMonth.isSupported( 
                ChronoUnit.MONTHS); 
  
        // print result 
        System.out.println("MONTHS unit is supported by YearMonth class:"
                           + value); 
    } 
}
輸出:
YearMonth:2017-08
MONTHS unit is supported by YearMonth class:true

程序2:

// Java program to demonstrate 
// YearMonth.isSupported(TemporalUnit) method 
  
import java.time.*; 
import java.time.temporal.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create a YearMonth object 
        YearMonth thisYearMonth = YearMonth.of(2022, 12); 
  
        // print instance 
        System.out.println("YearMonth:"
                           + thisYearMonth); 
  
        // apply isSupported() method 
        boolean value 
            = thisYearMonth.isSupported( 
                ChronoUnit.MILLENNIA); 
  
        // print result 
        System.out.println("MILLENNIA unit is supported:"
                           + value); 
    } 
}
輸出:
YearMonth:2022-12
MILLENNIA unit is supported:true

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



相關用法


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