当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。