Java 中的 Instant compareTo() 方法


可以使用 Java 中 Instant 類的 compareTo() 方法比較兩個 Instant 物件。此方法需要一個引數,即要比較的 Instant 物件。

如果第一個 Instant 物件大於第二個 Instant 物件,則它返回正數,如果第一個 Instant 物件小於第二個 Instant 物件,則它返回負數,如果兩個 Instant 物件相等,則它返回零。

展示此方法的程式如下所示

示例

 線上演示

import java.time.*;
public class Demo {
   public static void main(String[] args) {
      Instant i1 = Instant.parse("2019-01-13T18:35:19.00Z");
      Instant i2 = Instant.parse("2019-01-13T16:10:35.00Z");
      System.out.println("The first Instant object is: " + i1);
      System.out.println("The second Instant object is: " + i2);
      int val = i1.compareTo(i2);
      if(val > 0)
         System.out.println("
The first Instant object is greater than the second Instant object");       else if(val < 0)          System.out.println("
The first Instant object is lesser than the second Instant object");       else          System.out.println("
The Instant objects are equal");    } }

輸出

The first Instant object is: 2019-01-13T18:35:19Z
The second Instant object is: 2019-01-13T16:10:35Z

The first Instant object is greater than the second Instant object

下面我們來理解一下上述程式。

首先顯示兩個 Instant 物件。然後,使用 compareTo() 方法對其進行比較,並使用 if else 語句顯示結果。演示此方法的程式碼片段如下

Instant i1 = Instant.parse("2019-01-13T18:35:19.00Z");
Instant i2 = Instant.parse("2019-01-13T16:10:35.00Z");
System.out.println("The first Instant object is: " + i1);
System.out.println("The second Instant object is: " + i2);
int val = i1.compareTo(i2);
if(val > 0)
   System.out.println("
The first Instant object is greater than the second Instant object"); else if(val < 0)    System.out.println("
The first Instant object is lesser than the second Instant object"); else System.out.println("
The Instant objects are equal");

更新於: 2019 年 7 月 30 日

3K+ 次瀏覽

啟動您的 職業生涯

完成課程即可獲得認證

開始學習
廣告