5

I am setting an alarm for which I take the Hour and Minutes from a TextView and the AM/PM through a Spinner. Here is how I initialize the Calendar object:

Calendar calen = Calendar.getInstance();
calen.set(Calendar.HOUR_OF_DAY, alarmHour); //alarmHour from TextView
calen.set(Calendar.MINUTE, alarmMinute); //alarmMinute from TextView
calen.set(Calendar.SECOND, 0);
calen.set(Calendar.MILLISECOND, 0);

if(amorpm.equals("PM") //amorpm from Spinner
{
    calen.set(Calendar.AM_PM, Calendar.PM);
}
else
{
    calen.set(Calendar.AM_PM, Calendar.AM);
}

The problem is the Hour value of this Calendar object is sometimes correct i.e. the value which the user enters in the TextView (and it is always 1 to 12). But sometimes, the value is equal to the current Hour. For example, if the current time is 11:30 pm, and I set the alarm for 9:30 am, then the Hour field has the value 11. One strange thing is that when I change the name of the Calendar object to something else, say cal, it works. But wont work later. What could be wrong ?

Thanks for your help!

Shubham
  • 780
  • 3
  • 13
  • 32

1 Answers1

12

I think the solution is to call calen.set(Calendar.HOUR, alarmHour); instead of calen.set(Calendar.HOUR_OF_DAY, alarmHour);

The trouble is you are setting the Calendar.HOUR_OF_DAY field and then setting the AM/PM field. "Hour of day" is hour in the full 24-hour day, and therefore using it in conjuction with AM/PM doesn't make sense. According to the Java documentation (http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html), when setting the time of day, if conflicting information is presented, then the most recently set information will be used according to the following combinations:

HOUR_OF_DAY

AM_PM + HOUR

Because you are setting the AM/PM field after the hour, the hour is taken from the Calendar.HOUR field, which is of course initialised to the current hour when you create the instance.

The naming of the variable is, of course, a red herring. That can't possibly affect it.

Community
  • 1
  • 1
adrian
  • 2,793
  • 1
  • 23
  • 26
  • That is indeed the mistake I am making. But I just noticed that when I select "PM" from the spinner and enter alarm hour "12" in `HOUR`, then it changes "PM" to "AM" in the alarm. Similarly, choosing "AM" and "12" changes it to "PM". It works fine for non-12 values though. – Shubham Sep 12 '12 at 18:58
  • 3
    `Calendar.HOUR` is only supposed to take the values 0-11 (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#HOUR) so it's probably trying to do something intelligent with rolling the AM/PM forward when you set it as 12. – adrian Sep 17 '12 at 08:58
  • Thanks for your answer. I decided to take values in `Calendar.HOUR_OF_DAY` and set AM/PM through my own logic since in the app I am taking values in 12-hour format only. – Shubham Sep 18 '12 at 14:57