import java.time.LocalDateTime;
import java.time.Duration;
public class TimeComparison {
public static void main(String[] args) {
// 创建两个 LocalDateTime 对象
LocalDateTime time1 = LocalDateTime.of(2023, 10, 1, 12, 0);
LocalDateTime time2 = LocalDateTime.of(2023, 10, 2, 14, 30);
// 比较两个时间是否相等
if (time1.equals(time2)) {
System.out.println("两个时间相等");
} else {
System.out.println("两个时间不相等");
}
// 使用 isBefore() 方法比较 time1 是否在 time2 之前
if (time1.isBefore(time2)) {
System.out.println("time1 在 time2 之前");
} else {
System.out.println("time1 不在 time2 之前");
}
// 使用 isAfter() 方法比较 time1 是否在 time2 之后
if (time1.isAfter(time2)) {
System.out.println("time1 在 time2 之后");
} else {
System.out.println("time1 不在 time2 之后");
}
// 计算两个时间之间的差值
Duration duration = Duration.between(time1, time2);
System.out.println("两个时间之间相差 " + duration.toHours() + " 小时 " + duration.toMinutesPart() + " 分钟");
}
}
LocalDateTime
对象:我们使用 LocalDateTime.of()
方法创建了两个表示具体日期和时间的对象 time1
和 time2
。equals()
方法来判断两个时间是否完全相同。isBefore()
和 isAfter()
方法分别判断一个时间是否在另一个时间之前或之后。Duration.between()
方法计算两个时间之间的差值,并输出为小时和分钟的形式。希望这段代码能帮助你理解如何在 Java 中比较时间的大小。
上一篇:boolean在java中的用法
下一篇:java string 长度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站