📜  Java中的 Duration compareTo(Duration) 方法及示例

📅  最后修改于: 2022-05-13 01:55:17.900000             🧑  作者: Mango

Java中的 Duration compareTo(Duration) 方法及示例

Java.time 包Duration 类compareTo(Duration)方法用于比较这个持续时间和作为参数传递的持续时间。

句法:

public int compareTo(Duration otherDuration)

参数:此方法接受参数otherDuration ,该参数是与此持续时间进行比较的持续时间。

返回值:该方法返回一个int值,负值表示otherDuration大于该值,0表示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 文档