我的文件从日期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]);
答案 0 :(得分:3)
LocalDate x = new LocalDate(dateX);
LocalDate y = new LocalDate(dateY);
int i = Days.daysBetween(x, y).getDays();
missingdays = originalSizeofList - i;
这是joda-time,它比香草java容易得多。
答案 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;
}