温馨提示×

java怎么比较两个可能为空的时间

小亿
122
2023-08-05 11:14:19
栏目: 编程语言

在Java中,可以使用LocalDateTime类来比较两个可能为空的时间。下面是一个比较两个LocalDateTime对象的示例代码:

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异常。

0