我必须找到今天日期和另一个上一个日期之间的日差。我怎么能找到??
我写了代码:
Calendar calfromDate = Calendar.getInstance();
calfromDate.set(m_nVYear, m_nVMonth, m_nVDay);
long m_lDate = calfromDate.getTimeInMillis();
Calendar calToday = Calendar.getInstance();
long today = calToday.getTimeInMillis();
Log.d("debug", "today:" +today);
Log.d("debug", "from date:" +m_lDate);
int day_difference = (int)((m_lDate - today)/(24*60*60*1000));
答案 0 :(得分:1)
来自http://tripoverit.blogspot.com/2007/07/java-calculate-difference-between-two.html:
public static long daysBetween(Calendar startDate, Calendar endDate) {
Calendar date = (Calendar) startDate.clone();
long daysBetween = 0;
while (date.before(endDate)) {
date.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
答案 1 :(得分:0)
尝试使用以下代码
// Creates two calendars instances
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
// Set the date for both of the calendar instance
cal1.set(2006, 12, 30);
cal2.set(2007, 5, 3);
// Get the represented date in milliseconds
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
// Calculate difference in milliseconds
long diff = milis2 - milis1;
// Calculate difference in seconds
long diffSeconds = diff / 1000;
// Calculate difference in minutes
long diffMinutes = diff / (60 * 1000);
// Calculate difference in hours
long diffHours = diff / (60 * 60 * 1000);
// Calculate difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("In milliseconds: " + diff + " milliseconds.");
System.out.println("In seconds: " + diffSeconds + " seconds.");
System.out.println("In minutes: " + diffMinutes + " minutes.");
System.out.println("In hours: " + diffHours + " hours.");
System.out.println("In days: " + diffDays + " days.");