我檢查,如果日期是在Java中兩個日期之間的標準方法是這樣的:檢查日期範圍之間的日期也處理空值的Java
public static boolean isWithinRange(Date date, Date startDate, Date endDate) {
return !(date.before(startDate) || date.after(endDate));
}
我要添加上的startDate空值的支持或endDate(意味着用戶沒有輸入日期,如果startDate爲空,我只想檢查endDate,如果endDate爲空,我只想檢查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));
}
替代更可讀的示例:
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));
}
但它感覺非常糟糕的代碼。有沒有其他方法可以解決這個問題?
讀書。但是你可能會考慮這是否會更適合codereview.stackexchange.com。 – JETM
這是爲了包容,而不是嚴格的前後。 – uraza
assylias的答案是最好的,但代碼的第二個版本非常合理。 – VGR