我想比較2天(實際上是3)。在我的使用案例中,我需要比較3個日期。一個是StartSleepingTime,StopSleepingTime和Now。我的應用程序監視用戶的活動級別,並且我有一個每半小時運行一次的計劃任務任務,以檢查NOW是否在用戶的StartSleepingTime和StopSleepingTime之間,以確保在此間隔內停止活動監控服務。由於用戶在運行計劃任務時第一次登錄時設置了StartSleepingTime和StopSleepingTime,與NOW相比,它們都處於「過去」狀態。目前,我試圖從3個日期只提取小時和分鐘的信息,做這樣的比較:僅比較Java中的小時和分鐘的2個日期?
public static boolean compareHrsAndMintsOnly(Date startSH, Date now, Date stopSH) {
boolean isNowWithinSleepingTime = false;
Calendar startSHCalendar = Calendar.getInstance();
startSHCalendar.setTime(startSH);
Calendar nowCalendar = Calendar.getInstance();
nowCalendar.setTime(now);
Calendar stopSHCalendar = Calendar.getInstance();
stopSHCalendar.setTime(stopSH);
int startSHhour = startSHCalendar.get(Calendar.HOUR_OF_DAY);
int startSHmin = startSHCalendar.get(Calendar.MINUTE);
int nowHour = nowCalendar.get(Calendar.HOUR_OF_DAY);
int nowMin = nowCalendar.get(Calendar.MINUTE);
int stopSHhour = stopSHCalendar.get(Calendar.HOUR_OF_DAY);
int stopSHmin = stopSHCalendar.get(Calendar.MINUTE);
if ((startSHhour > nowHour && startSHmin > nowMin) && (nowHour < stopSHhour && nowMin < stopSHmin)) {
// stop the monitoring service
isNowWithinSleepingTime = true;
}else {
// start the monitoring service
isNowWithinSleepingTime = false;
}
return isNowWithinSleepingTime;
}
但這並不出於某種原因。另外,我覺得必須有更好的方法來實現比較。任何建議請!
謝謝你的建議。我現在將測試它是否有效。看起來很簡單,容易理解! :) –
我接受了你的答案,因爲它是最容易實現的,它是可靠的(圖書館被證明是好的)。再次感謝! –
剛剛測試過。當startSH和stopSH過去時,它不起作用:/ –