Java重叠日期

时间:2015-01-07 06:51:26

标签: java

我有这个编程练习,寻找重叠的日期范围。

到目前为止,这就是我所做的:

  private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
private static final Date invalidDate = new Date(0);

private static final Date fromString( String spec ) {
    try {
        return dateFormat.parse( spec );
    } catch( ParseException dfe ) {
        return invalidDate;
    }
}

public static void main(String[] args) {

    Date [] randomDates = {
            fromString("Aug 28, 2014"), 
            fromString("Sep 1, 2014"), 
            fromString("Aug 30, 2014"), 
            fromString("Sep 3, 2014"), 
            fromString("Sep 5, 2014"),
            fromString("Sep 7, 2014")
        };

    for( Date date: randomDates ) {
        print( date );
    }

}

private static final void print( Date date ) {
    if( date == invalidDate ) {
        System.out.println("Invalid date");
    } else {
        System.out.println( dateFormat.format( date ) );
    }
}

但我似乎无法弄清楚日期的重叠。或者我仍然不知道如何找到重叠的日期。有任何想法吗?我们将非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

要检查重叠日期范围,您可以使用JodaTime

DateTime currentdate1 = DateTime.now(); //first Date range
DateTime endDate1 = now.plusHours(10);

DateTime currentdate2 = now.plusDays(5); //second Date range
DateTime endDate2 = now.plusDays(6);

Interval interval1 = new Interval( currentdate1, endDate1  );
Interval interval2 = new Interval( currentdate2, endDate2  );

System.out.println( interval1.overlaps( interval2 ) );

编辑: -

由于您不想使用外部库,因此可以使用Date的.compareTo()并尝试实现以下条件: -

( currentdate1 <= endDate2 and currentdate2 <= endDate1 )

实施例: -

if( (currentdate1.compareTo(endDate2)<=0) && (currentdate2.compareTo(endDate1)<=0) ){
//ranges overlap
}

由于您想要比较一个日期并检查它是否存在于指定的范围内,您可以执行以下操作: -

| Daterange start------Your Date------ DateRange ends|

因此: -

for(Date date:randomDates){
//check if the date in in the range
if( (DateRangeStart.compareTo(date)<=0) && (date.compareTo(DateRangeEnd)<=0)){
//date overlaps
System.out.println(dateFormat.format(date));
}
}

编辑: - 更新答案以包含问题的解决方案,如聊天

中所述
outerloop: for (int i = 0; i < (dates.length - 1); i = i + 2) {
            Date currentdate1 = dates[i];
            Date endDate1 = dates[i + 1];

            for (int j = i + 2; j < dates.length - 1; j = j + 2) {
                Date currentdate2 = dates[j];
                Date endDate2 = dates[j + 1];

                if ((currentdate1.compareTo(endDate2) <= 0)
                        && (currentdate2.compareTo(endDate1) <= 0)) {
                    System.out.println("Overlapping found:-");
                    print(currentdate2);
                    print(endDate2);
                    break outerloop;

                }
            }
        }