Duration compareTo() 方法在 Java 中
在 Java 中的 Duration 类中使用 compareTo() 方法即可比较两个时间段。此方法需要单个参数,即要比较的时间段。
如果第一个时间段大于第二个时间段,则返回正数;如果第一个时间段小于第二个时间段,则返回负数;如果两个时间段相等,则返回零。
演示此方法的一个程序如下 -
示例
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("
The first duration is greater than the second duration");
else if(val < 0)
System.out.println("
The first duration is lesser than the second duration");
else
System.out.println("
The 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("
The first duration is greater than the second duration");
else if(val < 0)
System.out.println("
The first duration is lesser than the second duration");
else
System.out.println("
The durations are equal");
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP