Abhishek Singh Abhishek Singh - 9 months ago 34
Android Question

Alarm is setting 12 hours later in my Alarm android app whenever the time is 12:xx PM

I a building an alarm app in android. But whenever the time is 12 in noon. it automatically set the alarm 12 hours later. like If I am setting the alarm at 10:00 it is then setting it to 22:00. And If I am setting the alarm at 14:00 it is setting the alarm at 02:00 the next day.
This error is only happening when my android clock says 12.xx.

I am taking the time and date from a button text..
Here is the code and the log.

Date today = c.getTime();

setAlarmTimeAndDate = Calendar.getInstance();
setAlarmTimeAndDate.set(Calendar.DATE, Integer.parseInt(saveDateButton.getText().toString().substring(0, 2)));
setAlarmTimeAndDate.set(Calendar.MONTH, Integer.parseInt(saveDateButton.getText().toString().substring(3, 5)) - 1);
setAlarmTimeAndDate.set(Calendar.YEAR, Integer.parseInt(saveDateButton.getText().toString().substring(6, 10)));
setAlarmTimeAndDate.set(Calendar.HOUR, Integer.parseInt(saveTimeButton.getText().toString().substring(0, 2)));
setAlarmTimeAndDate.set(Calendar.MINUTE, Integer.parseInt(saveTimeButton.getText().toString().substring(3, 5)));

Log.d("currentDateAndTime", c.getTime().toString());
Log.d("ButtonDateAndTime|alarm", saveDateButton.getText().toString()
+ "|" + saveTimeButton.getText().toString()
+ "|" +setAlarmTimeAndDate.getTime().toString());


logs:

03-12 02:31:39.814 6896-6896/com.codedweeb.notesandmemo D/currentDateAndTime: Sun Mar 12 02:31:28 GMT+05:30 2017
03-12 02:31:39.814 6896-6896/com.codedweeb.notesandmemo D/ButtonDateAndTime|alarm: 12/03/2017|03:30 AM|Sun Mar 12 03:30:39 GMT+05:30 2017

03-12 12:33:20.366 6896-6896/com.codedweeb.notesandmemo D/currentDateAndTime: Sun Mar 12 12:33:18 GMT+05:30 2017
03-12 12:33:20.366 6896-6896/com.codedweeb.notesandmemo D/ButtonDateAndTime|alarm: 12/03/2017|03:30 AM|Sun Mar 12 15:30:20 GMT+05:30 2017


I changed the time of my phone and then it put alarm 12 hours late.

Answer Source

You should use Calendar.HOUR_OF_DAY instead of Calendar.HOUR. You must be facing this issue from 12 to 24 hour of day. Calendar.HOUR is used for 12 hour clock system, while Calender.HOUR_OF_DAY is used for 24 hour clock system.

When new instance of Calendar object been cleated after 12 hour,time was in PM(after 12), you tried to set Calender.HOUR as 3, so it's making it 3 PM, mean 15 hour.