0

Depending on the time of the day, I am setting an alarm, defined by alarmTime, for a certain time. If it's before 9am, then one condition runs, if it's between 9am-11am, another condition runs, and it it's after 11am, another condition runs. However, after 9am the if(currentTime.before(at9)) returns true, regardless of whether its 12pm, 1pm, etc, when it should return false. Why does this happen?

     // 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);
    }
Nicolae Stroncea
  • 587
  • 2
  • 6
  • 17

1 Answers1

0

As mentioned by Pankaj Kumar,Using Calendar.HOUR_OF_DAY solved the issue. Calendar.HOUR field is for a 12-hour format, Calendar.HOUR_OF_DAY is the 24-hour format.

Nicolae Stroncea
  • 587
  • 2
  • 6
  • 17