java 检查日期是否在给定的日期范围内

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40148120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:57:33  来源:igfitidea点击:

Check that date is within a given range of date inclusive

javadaterange

提问by Tian Na

This question is to compare dates inclusively in Java.

这个问题是在 Java 中比较日期。

Is there a better way to check if a given date is within a range inclusively?

有没有更好的方法来检查给定日期是否包含在一个范围内?

Date startDate, endDate, dateToCheck;

if ( dateToCheck.equals(startDate) || 
     dateToCheck.equals(endDate) || 
    (dateToCheck.after(startDate) && dateToCheck.before(endDate) ) 

回答by Eran

You can avoid the equalschecks by checking that the given date is not before or after the range :

您可以equals通过检查给定日期不在范围之前或之后来避免检查:

if (!dateToCheck.before (startDate) && !dateToCheck.after (endDate))

回答by Lestyán Mihály

You can always use the compareTo method for inclusive date ranges:

您始终可以对包含的日期范围使用 compareTo 方法:

public boolean checkBetween(Date dateToCheck, Date startDate, Date endDate) {
    return dateToCheck.compareTo(startDate) >= 0 && dateToCheck.compareTo(endDate) <=0;
}

回答by smsnheck

If you are using Joda DateTime there is a specific method you can use from the Interval class: interval.contains(date). You can convert your Java date very easy to the Joda Interval and DateTime.

如果您使用的是 Joda DateTime,则可以使用 Interval 类中的特定方法:interval.contains(date). 您可以非常轻松地将 Java 日期转换为 Joda Interval 和 DateTime。

See herefor more informations about the contains method.

有关contains 方法的更多信息,请参见此处

Edit saw your edit just now (I assume that you are using Java Date):

编辑刚刚看到您的编辑(我假设您使用的是 Java Date):

Interval interval = new Interval(startDate.getTime(), endDate.getTime()); interval.contains(dateToCheck.getTime());

Interval interval = new Interval(startDate.getTime(), endDate.getTime()); interval.contains(dateToCheck.getTime());