2013-06-20 90 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