2012-05-14 113 views
2

我想計算兩個日期之間的差異。 目前,我做:Java中的日期差異計算

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。但我想,我應該得到的輸出0時,新的Date()爲15.目前新的日期14.這讓我進一步計算錯誤,我很困惑如何解決這個問題。請建議。

回答

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

+0

thnx您附加的例子幫助我計算差異。 – Mohit224

+0

沒問題@ Mohit224。前幾天進入類似的情況。 – pacman

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(); 

所以你可以看到你可以那麼簡單,因爲從一個減另一個...