Java 中的 LocalDateTime isSupported() 方法


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

如下所示,提供了一個對此進行演示的程式 −

 即時演示

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

輸出

The LocalDateTime is: 2019-02-18T07:12:12.472
The ChronoUnit HOURS is supported

現在我們來了解一下上述程式。

首先,顯示當前時間。然後,使用 isSupported() 方法來檢查 ChronoUnit HOURS 是否受 LocalDateTime 類的支援。將返回的值儲存在 flag 中,並打印出相應的響應。如下所示,提供了一個對此進行演示的程式碼片段 −

LocalDateTime ldt = LocalDateTime.now();
System.out.println("The LocalDateTime is: " + ldt);
boolean flag = ldt.isSupported(ChronoUnit.HOURS);
if(flag)
   System.out.println("The ChronoUnit HOURS is supported");
else
   System.out.println("The ChronoUnit HOURS is not supported");

更新於: 2019 年 7 月 30 日

76 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.