在这里,您只需要做简单的数学运算。
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.");
这在跨越夏令时(或闰秒)时不起作用,并且在使用一天中的不同时间时也可能不会给出预期的结果。您可以像这样修改它:
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--;
}
希望这可以帮助。祝你好运。