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

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

How can I determine if a date is between two dates in Java?

javadate

提问by Gnaniyar Zubair

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?

在所有三个日期都由 的实例表示的情况下,如何检查日期是否在其他两个日期之间java.util.Date

采纳答案by Peter Lawrey

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;

回答by Jason Cohen

Like so:

像这样:

Date min, max;   // assume these are set to something
Date d;          // the date in question

return d.compareTo(min) >= 0 && d.compareTo(max) <= 0;

You can use >instead of >=and <instead of <=to exclude the endpoints from the sense of "between."

您可以使用>代替>=<代替<=来从“介于”的意义上排除端点。

回答by Nathan Feger

This might be a bit more readable:

这可能更具可读性:

Date min, max;   // assume these are set to something
Date d;          // the date in question

return d.after(min) && d.before(max);

回答by user54579

you can use getTime()and compare the returned long UTC values.

您可以使用getTime()和比较返回的长 UTC 值。

EDIT if you are sure you'll not have to deal with dates before 1970, not sure how it will behave in that case.

如果您确定不必处理 1970 年之前的日期,请编辑,不确定在这种情况下它会如何表现。

回答by David

Another option

另外一个选项

min.getTime() <= d.getTime() && d.getTime() <= max.getTime()

回答by willcodejavaforfood

You might want to take a look at Joda Timewhich is a really good API for dealing with date/time. Even though if you don't really need it for the solution to your current question it is bound to save you pain in the future.

您可能想看看Joda Time,它是一个非常好的处理日期/时间的 API。即使您真的不需要它来解决您当前的问题,它也一定会在未来为您省去痛苦。

回答by Biswabrata Banerjee

import java.util.Date;

public class IsDateBetween {

public static void main (String[] args) {

          IsDateBetween idb=new IsDateBetween("12/05/2010"); // passing your Date
 }
 public IsDateBetween(String dd) {

       long  from=Date.parse("01/01/2000");  // From some date

       long to=Date.parse("12/12/2010");     // To Some Date

       long check=Date.parse(dd);

       int x=0;

      if((check-from)>0 && (to-check)>0)
      {
             x=1;
      }

 System.out.println ("From Date is greater Than  ToDate : "+x);
}   

}

回答by Akshay Lokur

Here you go:

干得好:

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...");
        }
    }

回答by Basil Bourque

Here's a couple ways to do this using the Joda-Time2.3 library.

这是使用Joda-Time2.3 库执行此操作的几种方法。

One way is to use the simple isBeforeand isAftermethods on DateTimeinstances. By the way, DateTime in Joda-Time is similar in concept to a java.util.Date (a moment in time on the timeline of the Universe) but includes a time zone.

一种方法是在DateTime实例上使用 simpleisBeforeisAfter方法。顺便说一下,Joda-Time 中的 DateTime 在概念上类似于 java.util.Date(宇宙时间轴上的一个时刻),但包括一个时区。

Another way is to build an Interval in Joda-Time. The containsmethod tests if a given DateTime occurs within the span of time covered by the Interval. The beginning of the Interval is inclusive, but the endpoint is exclusive. This approach is known as "Half-Open", symbolically [).

另一种方法是在 Joda-Time 中构建一个 Interval。该contains方法测试给定的 DateTime 是否发生在 Interval 所涵盖的时间跨度内。Interval 的开始是包含的,但端点是独占的。这种方法被称为“半开”,象征性地[)

See both ways in the following code example.

请参阅以下代码示例中的两种方式。

Convert the java.util.Date instances to Joda-Time DateTimeinstances. Simply pass the Date instance to constructor of DateTime. In practice you should also pass a specific DateTimeZoneobject rather than rely on JVM's default time zone.

将 java.util.Date 实例转换为 Joda-TimeDateTime实例。只需将 Date 实例传递给 DateTime 的构造函数。在实践中,您还应该传递一个特定的DateTimeZone对象,而不是依赖 JVM 的默认时区。

DateTime dateTime1 = new DateTime( new java.util.Date() ).minusWeeks( 1 );
DateTime dateTime2 = new DateTime( new java.util.Date() );
DateTime dateTime3 = new DateTime( new java.util.Date() ).plusWeeks( 1 );

Compare by testing for before/after…

通过测试之前/之后进行比较...

boolean is1After2 = dateTime1.isAfter( dateTime2 );
boolean is2Before3 = dateTime2.isBefore( dateTime3 );

boolean is2Between1And3 = ( ( dateTime2.isAfter( dateTime1 ) ) && ( dateTime2.isBefore( dateTime3 ) ) );

Using the Interval approach instead of isAfter/isBefore…

使用 Interval 方法而不是 isAfter/isBefore...

Interval interval = new Interval( dateTime1, dateTime3 );
boolean intervalContainsDateTime2 = interval.contains( dateTime2 );

Dump to console…

转储到控制台...

System.out.println( "DateTimes: " + dateTime1 + " " + dateTime1 + " " + dateTime1 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
System.out.println( "is2Between1And3 " + is2Between1And3 );
System.out.println( "intervalContainsDateTime2 " + intervalContainsDateTime2 );

When run…

运行时…

DateTimes: 2014-01-22T20:26:14.955-08:00 2014-01-22T20:26:14.955-08:00 2014-01-22T20:26:14.955-08:00
is1After2 false
is2Before3 true
is2Between1And3 true
intervalContainsDateTime2 true

回答by ACV

Here's how to find whether today is between 2 months:

以下是如何确定今天是否在 2 个月之间:

private boolean isTodayBetween(int from, int to) {
    if (from < 0 || to < 0 || from > Calendar.DECEMBER || to > Calendar.DECEMBER) {
        throw new IllegalArgumentException("Invalid month provided: from = " + from + " to = " + to);
    }
    Date now = new Date();
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(now);
    int thisMonth = cal.get(Calendar.MONTH);
    if (from > to) {
        to = to + Calendar.DECEMBER;
        thisMonth = thisMonth + Calendar.DECEMBER;
    }
    if (thisMonth >= from && thisMonth <= to) {
        return true;
    }
    return false;
}

and call it like:

并称之为:

isTodayBetween(Calendar.OCTOBER, Calendar.MARCH)