Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); start.set(2010, 7, 23); end.set(2010, 8, 26); Date startDate = start.getTime(); Date endDate = end.getTime(); long startTime = startDate.getTime(); long endTime = endDate.getTime(); long diffTime = endTime - startTime; long diffDays = diffTime / (1000 * 60 * 60 * 24); DateFormat dateFormat = DateFormat.getDateInstance(); System.out.println("The difference between "+ dateFormat.format(startDate)+" and "+ dateFormat.format(endDate)+" is "+ diffDays+" days.");如orange80所指出的,在超过夏令时(或leap秒)时,这将不起作用,并且在一天中的不同时间使用时,也可能无法给出预期的结果。使用JodaTime可能更容易获得正确的结果,因为我知道8之前纯Java的唯一正确方法是使用Calendar的add和before/ after方法检查和调整计算:
start.add(Calendar.DAY_OF_MONTH, (int)diffDays); while (start.before(end)) { start.add(Calendar.DAY_OF_MONTH, 1); diffDays++; } while (start.after(end)) { start.add(Calendar.DAY_OF_MONTH, -1); diffDays--; }


