检查日期范围之间的日期是否也处理空值Java

ura*_*aza 4 java date date-comparison

检查日期是否在Java中的两个日期之间的标准方法如下所示:

public static boolean isWithinRange(Date date, Date startDate, Date endDate) {
    return !(date.before(startDate) || date.after(endDate));
}
Run Code Online (Sandbox Code Playgroud)

我想在startDate或endDate上添加对null值的支持(意味着用户没有输入日期.如果startDate为null,我只想检查endDate,如果endDate为null,我只想检查startDate,如果两者都是null,那么它是是的.我目前的解决方案如下:

public static boolean isWithinRange(Date date, Date startDate, Date endDate) {
    if (startDate == null && endDate == null) {
        return true;
    }

    if (!(startDate != null || !date.after(endDate))) {
        return true;
    }

    if (!(endDate != null || !date.before(startDate))) {
        return true;
    }

    return !(date.before(startDate) || date.after(endDate));
}
Run Code Online (Sandbox Code Playgroud)

替代更可读的例子:

public static boolean isWithinRange(Date date, Date startDate, Date endDate) {
    if (startDate == null && endDate == null) {
        return true;
    }

    if (startDate == null && date.before(endDate))) {
        return true;
    }

    if (endDate == null && date.after(startDate))) {
        return true;
    }

    return date.after(startDate) && date.before(endDate));
}
Run Code Online (Sandbox Code Playgroud)

但感觉真的很糟糕.有没有其他方法来处理这个?

ass*_*ias 10

怎么样:

return (startDate == null || !date.before(startDate))
    && (endDate == null || !date.after(endDate));
Run Code Online (Sandbox Code Playgroud)

这使用了这两个语句是等价的事实:

!(date.before(startDate) || date.after(endDate))
!date.before(startDate) && !date.after(endDate)
Run Code Online (Sandbox Code Playgroud)

而且这||是一个短路的事实,它阻止了NullPointerExceptions.