java.time.Instant.compareTo()方法

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.zaixian;

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.

上一篇: java.time.Instant類 下一篇: java.time.LocalDate類