如何确定日期是否在 Java 中的两个日期之间? [英] How can I determine if a date is between two dates in Java?
本文介绍了如何确定日期是否在 Java 中的两个日期之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果所有三个日期都由 java.util.Date
的实例表示,我如何检查一个日期是否在其他两个日期之间?
How can I check if a date is between two other dates, in the case where all three dates are represented by instances of java.util.Date
?
推荐答案
如果您不知道最小值/最大值的顺序
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;
}
这篇关于如何确定日期是否在 Java 中的两个日期之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文