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");热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短