且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何确定日期是否在 Java 中的两个日期之间?

更新时间:2023-01-27 17:35:04

如果您不知道最小值/最大值的顺序

If you don't know the order of the min/max values

Date a, b;   // assume these are set to something
Date d;      // the date in question

return a.compareTo(d) * d.compareTo(b) > 0;

如果您希望范围包含在内

If you want the range to be inclusive

return a.compareTo(d) * d.compareTo(b) >= 0;

您可以将 null 视为不受约束的

You can treat null as unconstrained with

if (a == null) {
    return b == null || d.compareTo(b) < 0;
} else if (b == null) {
    return a.compareTo(d) < 0;
} else {
    return a.compareTo(d) * d.compareTo(b) > 0;
}