2015-01-07 75 views
1

我有這個編程練習,它尋找重疊的日期範圍。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)); 
    } 
} 

但我似乎無法找出日期重疊。或者我仍然不知道如何找到重疊的日期。有任何想法嗎?您的幫助將得到真正的讚賞。

+0

可能重複的[確定是否兩個日期範圍重疊](http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap) –

+0

一種方法是獲得絕對毫秒,然後在範圍上進行數學運算。注意:絕對毫秒從1970年開始計算。 – Sid

回答

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)); 

編輯: -

既然你不想使用外部庫,你可以使用日期.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; 

       } 
      } 
     } 
+0

這很棒,但我不想使用任何外部庫。考慮到我正在解決的問題,我需要顯示數組中的重疊日期事件 –

+0

我已經更新了答案:) –

+0

謝謝,但我如何在日期數組中使用它? –