提供一個基於 java.util.Calendar 的工具方法,精確計算兩個 Date 物件之間的天數差異,忽略時間部分(時、分、秒、毫秒),適用於業務邏輯中需比較日期間隔的場景。
/**
* 計算兩個日期之間的天數差
* @param now 起始日期
* @param returnDate 結束日期
* @return 相差天數 (正數表示 now 在 returnDate 之後)
*/
private int daysBetween(Date now, Date returnDate) {
Calendar cNow = Calendar.getInstance();
Calendar cReturnDate = Calendar.getInstance();
cNow.setTime(now);
cReturnDate.setTime(returnDate);
// 將時間重置為當天 00:00:00,忽略時間影響
setTimeToMidnight(cNow);
setTimeToMidnight(cReturnDate);
long todayMs = cNow.getTimeInMillis();
long returnMs = cReturnDate.getTimeInMillis();
long intervalMs = todayMs - returnMs;
return millisecondsToDays(intervalMs);
}
/**
* 毫秒數轉換為天數
*/
private int millisecondsToDays(long intervalMs) {
return (int) (intervalMs / (1000 * 60 * 60 * 24)); // 1000*86400
}
/**
* 將 Calendar 時間設為當天午夜 (00:00:00)
*/
private void setTimeToMidnight(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0); // 建議補上毫秒
}
若專案使用 Java 8 或更新版本,強烈建議使用 java.time 套件,程式碼更簡潔且線程安全:
import java.time.LocalDate;
import java.temporal.ChronoUnit;
public long daysBetweenModern(LocalDate start, LocalDate end) {
return ChronoUnit.DAYS.between(start, end);
}
注意: 此範例使用舊版 Date/Calendar API,僅供維護舊專案參考。新專案請優先使用
java.time.LocalDate。