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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With