检查日期是否在 Java 中的两个日期之间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2896173/
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-08-13 14:12:57  来源:igfitidea点击:

Check a Date is between two dates in Java

javadate

提问by dimitar

One thing I want to know is how to calculate what date will it be 10 days from today.

我想知道的一件事是如何计算从今天起 10 天后的日期。

Second thing is to check if one Date is between two other Dates. For example, let's say I have an app that shows what events I need to do in the next 10 days (planner). Now how can I see if the date I assigned to an event is between today and the date that is 10 days from today?

第二件事是检查一个日期是否在其他两个日期之间。例如,假设我有一个应用程序,可以显示我在接下来的 10 天内需要执行的事件(计划程序)。现在如何查看我分配给事件的日期是否在今天和距今天 10 天后的日期之间?

回答by Rune Molin

Use JodaTime calendar replacement classes: http://joda-time.sourceforge.net/

使用 JodaTime 日历替换类:http://joda-time.sourceforge.net/

回答by Andrei Fierbinteanu

To add ten days:

添加十天:

Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_YEAR, 10);

To check if between two dates:

要检查是否在两个日期之间:

myDate.after(firstDate) && myDate.before(lastDate);

回答by Lalith

You can find more answers here

你可以在这里找到更多答案

回答by BalusC

Manipulating and comparing dates using java.util.Dateand java.util.Calendaris pretty a pain, that's why JodaTimeexist. None of the answers as far have covered the timein question. The comparisons may fail when the dates have a non-zero time. It's also unclear whether you want an inclusiveor exclusivecomparison. Most of the answers posted so far suggest exclusivecomparision (i.e. May 24 is notbetween May 20 and May 24) while in real it would make more sense to make it inclusive(i.e. May 24 isbetween May 20 and May 24).

使用java.util.Date和操作和比较日期java.util.Calendar非常痛苦,这就是JodaTime存在的原因。到目前为止,没有一个答案涵盖了所讨论的时间。当日期具有非零时间时,比较可能会失败。还不清楚您是要进行包容性比较还是排斥性比较。到目前为止发布的大多数答案都建议进行排他性比较(即 5 月 24 日不在5 月 20 日和 5 月 24 日之间),而实际上将其包含在内(即 5 月 24 日在 5 月 20 日和 5 月 24 日之间)会更有意义。



One thing I want to know is how to calculate what date will it be 10 days from today.

我想知道的一件事是如何计算从今天起 10 天后的日期。

With the standard Java SE 6 API, you need java.util.Calendarfor this.

使用标准的 Java SE 6 API,您需java.util.Calendar要这样做。

Calendar plus10days = Calendar.getInstance();
plus10days.add(Calendar.DAY_OF_YEAR, 10);

With JodaTime you would do like this:

使用 JodaTime,您可以这样做:

DateTime plus10days = new DateTime().plusDays(10);


Second thing is to check if one Date is between two other Dates. For example, let's say I have an app that shows what events I need to do in the next 10 days (planner). Now how can I see if the date I assigned to an event is between today and the date that is 10 days from today?

第二件事是检查一个日期是否在其他两个日期之间。例如,假设我有一个应用程序,可以显示我在接下来的 10 天内需要执行的事件(计划程序)。现在如何查看我分配给事件的日期是否在今天和距今天 10 天后的日期之间?

Now comes the terrible part with Calendar. Let's prepare first:

现在到了可怕的部分Calendar。我们先准备一下:

Calendar now = Calendar.getInstance();
Calendar plus10days = Calendar.getInstance();
plus10days.add(Calendar.DAY_OF_YEAR, 10);
Calendar event = Calendar.getInstance();
event.set(year, month - 1, day); // Or setTime(date);

To compare reliably using Calendar#before()and Calendar#after(), we need to get rid of the time first. Imagine it's currently 24 May 2010 at 9.00 AM and that the event's date is set to 24 May 2010 without time. When you want inclusive comparison, you would like to make it return trueat the same day. I.e. both the (event.equals(now) || event.after(now))or -shorter but equally- (!event.before(now))should return true. But actually none does that due to the presence of the time in now. You need to clear the time in all calendar instances first like follows:

为了比较可靠地使用Calendar#before()and Calendar#after(),我们需要先摆脱时间。假设现在是 2010 年 5 月 24 日上午 9 点,并且事件的日期设置为 2010 年 5 月 24 日,但没有时间。当您想要包容性比较时,您希望return true在同一天进行。即(event.equals(now) || event.after(now))或 - 更短但同样 -(!event.before(now))都应该返回true。但实际上没有人这样做,因为now. 您需要先清除所有日历实例中的时间,如下所示:

calendar.clear(Calendar.HOUR);
calendar.clear(Calendar.HOUR_OF_DAY);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);

Alternatively you can also compare on day/month/year only.

或者,您也可以仅按日/月/年进行比较。

if (event.get(Calendar.YEAR) >= now.get(Calendar.YEAR)
    && event.get(Calendar.MONTH) >= now.get(Calendar.MONTH)
    && event.get(Calendar.DAY_OF_MONTH) >= now.get(Calendar.DAY_OF_MONTH)
{
    // event is equal or after today.
}

Very verbose all.

非常冗长。

With JodaTime you can just use DateTime#toLocalDate()to get the date part only:

使用 JodaTime,您只能使用DateTime#toLocalDate()获取日期部分:

LocalDate now = new DateTime().toLocalDate();
LocalDate plus10days = now.plusDays(10);
LocalDate event = new DateTime(year, month, day, 0, 0, 0, 0).toLocalDate();
if (!event.isBefore(now) && !event.isAfter(plus10days)) {
    // Event is between now and 10 days (inclusive).
}

Yes, the above is really allyou need to do.

是的,上面真的是所有你需要做的。

回答by Krish Lakshmanan

public static boolean between(Date date, Date dateStart, Date dateEnd) {
    if (date != null && dateStart != null && dateEnd != null) {
        if (date.after(dateStart) && date.before(dateEnd)) {
            return true;
        }
        else {
            return false;
        }
    }
    return false;
}

EDIT: Another suggested variant:

编辑:另一个建议的变体:

public Boolean checkDate(Date startDate, Date endDate, Date checkDate) { 
    Interval interval = new Interval(new DateTime(startDate), 
                                     new DateTime(endDate));   
    return interval.contains(new DateTime(checkDate)); 
}

回答by technocrat

I took the initial answer and modified it a bit. I consider if the dates are equal to be "inside"..

我接受了最初的答案并对其进行了一些修改。我考虑日期是否等于“内部”..

private static boolean between(Date date, Date dateStart, Date dateEnd) {
    if (date != null && dateStart != null && dateEnd != null) {
        return (dateEqualOrAfter(date, dateStart) && dateEqualOrBefore(date, dateEnd));

    }
    return false;
}

private static boolean dateEqualOrAfter(Date dateInQuestion, Date date2)
{
    if (dateInQuestion.equals(date2))
        return true;

    return (dateInQuestion.after(date2));

}
private static boolean dateEqualOrBefore(Date dateInQuestion, Date date2)
{
    if (dateInQuestion.equals(date2))
        return true;

    return (dateInQuestion.before(date2));

}

回答by Akshay Lokur

To check if date is between two dates, here is simple program:

要检查日期是否在两个日期之间,这里是一个简单的程序:

public static void main(String[] args) throws ParseException {

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

    String oeStartDateStr = "04/01/";
    String oeEndDateStr = "11/14/";

    Calendar cal = Calendar.getInstance();
    Integer year = cal.get(Calendar.YEAR);

    oeStartDateStr = oeStartDateStr.concat(year.toString());
    oeEndDateStr = oeEndDateStr.concat(year.toString());

    Date startDate = sdf.parse(oeStartDateStr);
    Date endDate = sdf.parse(oeEndDateStr);
    Date d = new Date();
    String currDt = sdf.format(d);


    if((d.after(startDate) && (d.before(endDate))) || (currDt.equals(sdf.format(startDate)) ||currDt.equals(sdf.format(endDate)))){
        System.out.println("Date is between 1st april to 14th nov...");
    }
    else{
        System.out.println("Date is not between 1st april to 14th nov...");
    }
}