我想计算两个日期之间的差异。 目前,我正在做:
Calendar firstDate = Calendar.getInstance();
firstDate.set(Calendar.DATE, 15);
firstDate.set(Calendar.MONTH, 4);
firstDate.get(Calendar.YEAR);
int diff = (new Date().getTime - firstDate.getTime)/(1000 * 60 * 60 * 24)
这给了我输出0.但我希望当新的Date()为15时我应该得到输出0.目前新的日期是14.它使我的进一步计算错误,我很困惑如何解决这个问题。请建议。
答案 0 :(得分:3)
找出两个日期之间的差异并不像以前那么简单 减去两个日期并将结果除以(24 * 60 * 60 * 1000)。事实上,它的错误!
/* Using Calendar - THE CORRECT (& Faster) WAY**/
//assert: startDate must be before endDate
public static long daysBetween(final Calendar startDate, final Calendar endDate) {
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
long endInstant = endDate.getTimeInMillis();
int presumedDays = (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);
Calendar cursor = (Calendar) startDate.clone();
cursor.add(Calendar.DAY_OF_YEAR, presumedDays);
long instant = cursor.getTimeInMillis();
if (instant == endInstant)
return presumedDays;
final int step = instant < endInstant ? 1 : -1;
do {
cursor.add(Calendar.DAY_OF_MONTH, step);
presumedDays += step;
} while (cursor.getTimeInMillis() != endInstant);
return presumedDays;
}
您可以在此here上阅读更多内容。
答案 1 :(得分:1)
我不认为通过创建一个新的Date()会给你当前的时间和日期,而不是这样做:
Calendar cal = Calendar.getInstance();
Date currentDate = cal.getTime();
Date firstDate = new Date();
firstDate.setHour(...);
firstDate.setMinute(...);
firstDate.setSeconds(...);
long dif = currentDate.getTime() - firstDate.getTime();
所以你可以看到你可以像从另一个中减去一样直截了当......