Javatime-instant-compareto

提供:Dev Guides
移動先:案内検索

java.time.Instant.compareTo()メソッドの例

説明

  • java.time.Instant.compareTo(Instant otherInstant)*メソッドは、このインスタントを指定されたインスタントと比較します。

宣言

以下は、* java.time.Instant.compareTo(Instant otherInstant)*メソッドの宣言です。

public int compareTo(Instant otherInstant)

パラメーター

*otherInstant* -比較する他のインスタント、nullではない。

戻り値

コンパレータ値。小さい場合は負、大きい場合は正

例外

*NullPointerException* -otherInstantがnullの場合。

次の例は、java.time.Instant.compareTo(Instant otherInstant)メソッドの使用法を示しています。

package com.finddevguides;

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.