Java中的持续时间compareTo()方法
可以使用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()方法比较持续时间,并使用ifelse语句显示结果。演示这的代码片段如下-
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");热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语