Duration compareTo() 方法在 Java 中


在 Java 中的 Duration 類中使用 compareTo() 方法即可比較兩個時間段。此方法需要單個引數,即要比較的時間段。

如果第一個時間段大於第二個時間段,則返回正數;如果第一個時間段小於第二個時間段,則返回負數;如果兩個時間段相等,則返回零。

演示此方法的一個程式如下 -

示例

 線上示例演示

import java.time.Duration;
public class Demo {
   public static void main(String[] args) {
      Duration d1 = Duration.ofHours(8);
      Duration d2 = Duration.ofHours(6);
      System.out.println("The first duration is: " + d1);
      System.out.println("The second duration is: " + d2);
      int val = d1.compareTo(d2);
      if(val > 0)
         System.out.println("
The first duration is greater than the second duration"); else if(val < 0) System.out.println("
The first duration is lesser than the second duration"); else System.out.println("
The durations are equal"); } }

輸出

The first duration is: PT8H
The second duration is: PT6H
The first duration is greater than the second duration

現在讓我們理解上面的程式。

首先顯示兩個時間段。然後使用 compareTo() 方法比較這兩個時間段,並使用 if else 語句顯示結果。演示此方法的程式碼片段如下 -

Duration d1 = Duration.ofHours(8);
Duration d2 = Duration.ofHours(6);
System.out.println("The first duration is: " + d1);
System.out.println("The second duration is: " + d2);
int val = d1.compareTo(d2);
if(val > 0)
   System.out.println("
The first duration is greater than the second duration"); else if(val < 0) System.out.println("
The first duration is lesser than the second duration"); else System.out.println("
The durations are equal");

更新時間: 2019-7-30

7K+ 瀏覽

開始您的 職業生涯

完成課程以獲得認證

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