1

我有一份从 X 日开始到 Y 日结束的文件,并且增加了一天。我的任务是浏览这份文件并找出文件中缺少多少天。

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

2 回答 2

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

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

missingdays = originalSizeofList - i;

这是 joda-time,它比 vanilla java 容易得多。

于 2013-06-20T12:42:21.943 回答
3

与乔达时间。(如果你只关心日期,你不应该使用日期时间,或者弄乱小时、分钟、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;
}
于 2013-06-20T12:51:12.573 回答