2013-06-20 23 views
1

我有一個文檔,從日期X開始,在日期Y結束,並且上升一天。我的任務是查看這個文檔,找出文檔中缺少多少天。在java中使用日曆或Joda-Time

Example: 
19990904 56.00 
19990905 57.00 
19990907 60.00 

需要打印出19900906缺失。

我已經做了一些研究並閱讀了有關Java日曆,日期和Joda-Time的內容,但無法理解它們中的任何一個。有人可以解釋一下我剛纔提到的這些功能嗎,然後就如何使用它來實現我的目標提出建議?

我已經有這樣的代碼:

String name = getFileName(); 
BufferedReader reader = new BufferedReader(new FileReader(name)); 

String line; 

while ((line = reader.readLine()) != null) 
{ //while 
    String delims = "[ ]+"; 
    String [] holder = line.split(delims); 

    // System.out.println("*"); 

    int date = Integer.parseInt(holder[0]); 
    //System.out.println(holder[0]); 

    double price = Double.parseDouble(holder[1]); 

回答

3

隨着JodaTime。 (如果你只用日期而言,你不應該使用日期時間,或具時,分,DST問題的混亂。)

final DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyyMMdd"); 

LocalDate date=null; 
while((line = getNextLine())!=null) { 
    String dateAsString = line.split(delims)[0]; 
    LocalDate founddate = dtf.parseLocalDate(dateAsString); 
    if(date==null) { date= founddate; continue;} // first 
    if(founddate.before(date)) throw new RuntimeException("date not sorted?"); 
    if(founddate.equals(date)) continue; // dup dates are ok? 
    date = date.plusDays(1); 
    while(date.before(foundate)){ 
     System.out.println("Date not found: " +date); 
     date = date.plusDays(1); 
    } 
} 

如果你只需要數天失蹤:

LocalDate date=null; 
int cont=0; 
while((line = getNextLine())!=null) { 
    String dateAsString = line.split(delims)[0]; 
    LocalDate founddate = dtf.parseLocalDate(dateAsString); 
    if(date==null) { date= founddate; continue;} // first 
    if(founddate.before(date)) throw new RuntimeException("date not sorted?"); 
    if(founddate.equals(date)) continue; // dup dates are ok? 
    cont += Days.daysBetween(date, founddate)-1; 
    date = founddate; 
} 
+0

我需要導入任何東西才能使用JodaTime嗎? – Danny

+1

@Danny yeah jodatime本身http://mvnrepository.com/artifact/joda-time/joda-time/2.2 – NimChimpsky

+0

我因爲使用LocalDate和DateTimeFormatter – Danny

3
LocalDate x = new LocalDate(dateX); 
LocalDate y = new LocalDate(dateY); 

int i = Days.daysBetween(x, y).getDays(); 

missingdays = originalSizeofList - i; 

這是喬達時,其比香草的Java容易得多。

+0

+1在任何你想使用人類可讀字段操縱日期的地方使用Joda時間。 – Jim

+0

我剛剛更新了我的問題,我沒有提供足夠的信息,這是我的不好。我正在使用緩衝讀取器,並放棄每行(文件是20GB)陣列,所以我不認爲這會工作:-( – Danny

+1

這不會回答這個問題,因爲OP希望打印每一個缺少的一天,不僅僅是它們的計數 – Artyom