可以使用compareTo()
Java中Duration类中的方法比较两个持续时间。该方法需要一个参数,即要比较的持续时间。
如果第一持续时间大于第二持续时间,则返回正数;如果第一持续时间小于第二持续时间,则返回负数;如果两个持续时间相等,则返回零。
演示此的程序如下所示-
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("\nThe first duration is greater than the second duration"); else if(val < 0) System.out.println("\nThe first duration is lesser than the second duration"); else System.out.println("\nThe 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("\nThe first duration is greater than the second duration"); else if(val < 0) System.out.println("\nThe first duration is lesser than the second duration"); else System.out.println("\nThe durations are equal");