java怎样比较两个可能为空的时间
在Java中,可使用`LocalDateTime`类来比较两个可能为空的时间。下面是一个比较两个`LocalDateTime`对象的示例代码:
```java
import java.time.LocalDateTime;
public class TimeComparison {
public static void main(String[] args) {
LocalDateTime time1 = null; // 第一个时间
LocalDateTime time2 = LocalDateTime.now(); // 第二个时间
// 比较两个时间
if (time1 != null && time2 != null) {
// 如果两个时间都不为空
if (time1.isBefore(time2)) {
System.out.println("time1 is before time2");
} else if (time1.isAfter(time2)) {
System.out.println("time1 is after time2");
} else {
System.out.println("time1 is equal to time2");
}
} else if (time1 == null && time2 != null) {
// 如果第一个时间为空,第二个时间不为空
System.out.println("time1 is null");
} else if (time1 != null) {
// 如果第一个时间不为空,第二个时间为空
System.out.println("time2 is null");
} else {
// 如果两个时间都为空
System.out.println("Both times are null");
}
}
}
```
在上面的代码中,我们先判断两个时间是否是为空,如果不为空,则使用`isBefore()`、`isAfter()`和`isEqual()`方法来比较两个时间的前后关系。如果只有一个时间为空,则根据情况输出对应的提示信息。如果两个时间都为空,也输出相应的提示信息。
注意:在比较之前,应当先判断时间是否是为空,以免`NullPointerException`异常。
TOP