Instant 在 Java 中的 isSupported() 方法


可以使用 Java 中 Instant 類的 isSupported() 方法,檢查 Instant 類是否支援 ChronoUnit。此方法需要一個引數,即要檢查的 ChronoUnit。如果 Instant 類支援該 ChronoUnit,則返回 true,否則返回 false。

一個演示此方法的程式如下所示 −

示例

 即時演示

import java.time.*;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      Instant i = Instant.now();
      System.out.println("The current instant is: " + i);
      boolean flag = i.isSupported(ChronoUnit.SECONDS);
      if(flag)
         System.out.println("The ChronoUnit SECONDS is supported");
      else
         System.out.println("The ChronoUnit SECONDS is not supported");
   }
}

輸出

The current instant is: 2019-02-13T07:08:32.900Z
The ChronoUnit SECONDS is supported

現在讓我們理解一下上述程式。

首先顯示當前瞬時值。然後使用 isSupported() 方法檢查 Instant 類是否支援 ChronoUnit SECONDS。將返回值儲存在 flag 中,並打印出相應的響應。一個演示此方法的程式碼片段如下 −

Instant i = Instant.now();
System.out.println("The current instant is: " + i);
boolean flag = i.isSupported(ChronoUnit.SECONDS);
if(flag)
   System.out.println("The ChronoUnit SECONDS is supported");
else
   System.out.println("The ChronoUnit SECONDS is not supported");

更新於: 30-Jul-2019

115 次瀏覽

開啟你的 職業生涯

完成教程並獲得認證

開始
廣告
© . All rights reserved.