我想比较2天(实际上是3天).在我的用例中,我有3个日期需要比较.一个是StartSleepingTime,StopSleepingTime和Now.我的应用程序监视用户的活动级别,我有一个每半小时运行一次的scheduleeld任务,以检查NOW是否在用户的StartSleepingTime和StopSleepingTime之间,以确保在此间隔期间停止活动监视服务.由于用户在首次登录时设置了StartSleepingTime和StopSleepingTime,当我运行计划任务时,与NOW相比,两者都将处于“过去”状态.目前我正在尝试从3个日期中仅提取小时和分钟信息,并进行如下比较:
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;
}
但由于某些原因,这不起作用.另外,我感觉必须有更好的方法来实现比较.有任何建议请!