java比较LocalDateTime时间大小代码编写
时间: 2023-11-16 14:00:25 浏览: 112
要比较两个LocalDateTime对象的大小,可以使用compareTo()方法或isBefore()、isAfter()方法。下面是比较LocalDateTime时间大小的代码示例:
```
LocalDateTime dateTime1 = LocalDateTime.of(2022, 12, 3, 12, 8, 56);
LocalDateTime dateTime2 = LocalDateTime.of(2022, 12, 3, 10, 31, 35);
// 使用compareTo()方法比较
if (dateTime1.compareTo(dateTime2) > 0) {
System.out.println("dateTime1 is later than dateTime2");
} else if (dateTime1.compareTo(dateTime2) < 0) {
System.out.println("dateTime1 is earlier than dateTime2");
} else {
System.out.println("dateTime1 is equal to dateTime2");
}
// 使用isBefore()、isAfter()方法比较
if (dateTime1.isAfter(dateTime2)) {
System.out.println("dateTime1 is later than dateTime2");
} else if (dateTime1.isBefore(dateTime2)) {
System.out.println("dateTime1 is earlier than dateTime2");
} else {
System.out.println("dateTime1 is equal to dateTime2");
}
```
阅读全文