java time 比较大小
时间: 2023-07-01 15:18:04 浏览: 74
Java时间大小的比较.pdf
在Java中,可以使用`compareTo()`方法或者`isBefore()`和`isAfter()`方法来比较时间的大小。下面是一些示例代码:
使用`compareTo()`方法:
```java
LocalDateTime now = LocalDateTime.now();
LocalDateTime later = now.plusHours(5);
if (now.compareTo(later) < 0) {
System.out.println("now is earlier than later");
} else if (now.compareTo(later) == 0) {
System.out.println("now is equal to later");
} else {
System.out.println("now is later than later");
}
```
使用`isBefore()`和`isAfter()`方法:
```java
LocalDateTime now = LocalDateTime.now();
LocalDateTime later = now.plusHours(5);
if (now.isBefore(later)) {
System.out.println("now is earlier than later");
} else if (now.isEqual(later)) {
System.out.println("now is equal to later");
} else {
System.out.println("now is later than later");
}
```
这些方法都可以用于比较`LocalDateTime`、`LocalDate`、`LocalTime`、`ZonedDateTime`等对象。
阅读全文