Java Duration compareTo(Duration)方法及实例

Java Duration compareTo(Duration)方法及实例

java.time包中Duration类的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

参考资料。甲骨文文件

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程