根据一天中的时间,我将在一定时间内设置一个由alarmTime定义的警报。如果在上午9点之前,则运行一个条件;如果在上午9点至上午11点之间,则运行另一个条件,而在上午11点后,则运行另一个条件。但是,在上午9点之后,if(currentTime.before(at9))返回true,无论其12 pm、1pm等何时返回false。为什么会这样?
// Get a calendar instance for the actual alarm
Calendar alarmTime = Calendar.getInstance();
// get the current time
Calendar currentTime = (Calendar) alarmTime.clone();
// This will set the values to the calendar
currentTime.getTime();
//get the time at 9AM
Calendar at9 = (Calendar) alarmTime.clone();
at9.set(Calendar.HOUR, 9);
at9.set(Calendar.MINUTE,0);
at9.set(Calendar.SECOND,0);
// This will set the values to the calendar
at9.getTime();
//get the time at 11AM
Calendar at11 = (Calendar) alarmTime.clone();
at11.set(Calendar.HOUR, 11);
at11.set(Calendar.MINUTE,0);
at11.set(Calendar.SECOND,0);
// This will set the values to the calendar
at11.getTime();
if(currentTime.before(at9)){// if it's less than 9am right now
//set the alarm for 9am current day
//the day should stay the same
alarmTime.set(Calendar.HOUR_OF_DAY, Constants.REFRESH_TIME_HOUR);
alarmTime.set(Calendar.MINUTE,20);
alarmTime.set(Calendar.SECOND, 0);
}
else if(currentTime.after(at9) && currentTime.before(at11)){
// Day should stay the same
// Hour should stay he same
alarmTime.add(Calendar.MINUTE, Constants.REFRESH_TIME_MINUTES);
alarmTime.set(Calendar.SECOND, 0);
}
else{ //current time is after 11
alarmTime.add(Calendar.DAY_OF_YEAR,1);
alarmTime.set(Calendar.HOUR_OF_DAY, Constants.REFRESH_TIME_HOUR);
alarmTime.set(Calendar.MINUTE,1);
alarmTime.set(Calendar.SECOND, 0);
}
答案 0 :(得分:0)
如Pankaj Kumar所述,使用Calendar.HOUR_OF_DAY解决了该问题。 Calendar.HOUR字段是12小时格式,Calendar.HOUR_OF_DAY是24小时格式。