當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Duration compareTo(Duration)用法及代碼示例


java.time包中的Duration Class的compareTo(Duration)方法用於將該持續時間與作為參數傳遞的持續時間進行比較。

用法:

public int compareTo(Duration otherDuration)

參數:此方法接受參數otherDuration,該參數是將與該持續時間進行比較的持續時間。


返回值:此方法返回一個int值,其中負值表示otherDuration大於此值,零表示otherDuration等於該持續時間,正值表示此持續時間大於otherDuration。

以下示例說明了Duration.compareTo()方法:

示例1:

// Java code to illustrate compareTo() method 
  
import java.time.Duration; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Duration using parse() method 
        Duration duration1 
            = Duration.parse("P2DT3H4M"); 
  
        // Duration using ofDays() method 
        Duration duration2 
            = Duration.ofDays(10); 
  
        // Compare the durations 
        // using compareTo() method 
        System.out.println(duration1 
                               .compareTo(duration2)); 
    } 
}
輸出:
-1

示例2:

// Java code to illustrate compareTo() method 
  
import java.time.Duration; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Duration using ofHours() method 
        Duration duration1 
            = Duration.ofHours(5); 
  
        // Duration using ofHours() method 
        Duration duration2 
            = Duration.ofHours(5); 
  
        // Compare the durations 
        // using compareTo() method 
        System.out.println(duration1 
                               .compareTo(duration2)); 
    } 
}
輸出:
0

示例3:

// Java code to illustrate compareTo() method 
  
import java.time.Duration; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Duration using ofDays() method 
        Duration duration1 
            = Duration.ofDays(5); 
  
        // Duration using ofHours() method 
        Duration duration2 
            = Duration.ofHours(5); 
  
        // Compare the durations 
        // using compareTo() method 
        System.out.println(duration1 
                               .compareTo(duration2)); 
    } 
}
輸出:
1

參考: Oracle Doc



相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Duration compareTo(Duration) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。