java.time.Instant.compareTo()方法

2019-10-16 22:39:10

java.time.Instant.compareTo(Instant otherInstant)方法將此瞬間與指定的瞬間進行比較。

宣告

以下是java.time.Instant.compareTo(Instant otherInstant)方法的宣告。

public int compareTo(Instant otherInstant)

引數

  • otherInstant - 比較的另一個瞬間,而不是null

返回值

比較器值,如果更小則為負,如果更大則為正。

異常

  • NullPointerException - 如果otherInstantnull

範例

以下範例顯示了java.time.Instant.compareTo(Instant otherInstant)方法的用法。

package com.yiibai;

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Set;

public class InstantDemo {
   public static void main(String[] args) {

      Instant instant = Instant.parse("2017-02-03T10:37:30.00Z");
      System.out.println("Instant #1: " + instant);  

      Instant instant1 = Instant.parse("2017-03-03T10:37:30.00Z");
      System.out.println("Instant #2: " + instant1);  

      int result = instant.compareTo(instant1);
      System.out.println(result >1 ? "Instant #1 is greater than Instant #2."
         :"Instant #2 is greater than Instant #1.");  
   }
}

編譯並執行上面的程式,這將產生以下結果 -

Instant #1: 2017-02-03T10:37:30Z
Instant #2: 2017-03-03T10:37:30Z
Instant #2 is greater than Instant #1.