Search code examples
androiddialogandroid-timepickertime-format

Show TimePicker with 12 or 24 hour format in android


I have a problem with my TimePickerDialog. first detect if the user's device has the time in 12 or 24 hour format:

…
String format;
…
if (DateFormat.is24HourFormat(this)) {
Log.i("control","Format 24");
format=("24");
} else {
 Log.i("control","Format 12");
format=("12");
}
…

Now my intention is to show the TimePicker with the option of am or pm, depending on the format:

…
if(format.equals("24"){
view.setIs24HourView(true);
} else {
view.setIs24HourView(true);
} …

This is the complete code TimePickerDialog:

public class AlarmPreferencesActivity extends ListActivity
…
TimePickerDialog timePickerDialog = new TimePickerDialogs(this, new TimePickerDialog.OnTimeSetListener(){

            @Override
            public void onTimeSet(TimePicker view, int hours, int minutes) {

                Calendar newAlarmTime = Calendar.getInstance();
                newAlarmTime.set(Calendar.HOUR_OF_DAY, hours);
                newAlarmTime.set(Calendar.MINUTE, minutes);
                newAlarmTime.set(Calendar.SECOND, 0);
                alarm.setAlarmTime(newAlarmTime);
                alarmPreferenceListAdapter
                .setMathAlarm(getMathAlarm());
                alarmPreferenceListAdapter
                .notifyDataSetChanged();

            }},
            alarm.getAlarmTime().get(Calendar.HOUR_OF_DAY),
            alarm.getAlarmTime().get(Calendar.MINUTE), true);


        timePickerDialog.setCancelable(true);
        timePickerDialog.setCustomTitle(getLayoutInflater().inflate(R.layout.custom_hours, null));
        timePickerDialog.show();
        }

My problem is I do not know where to include view.setIs24HourView (true) or (false). I have tried many variations but nothing works. I searched for information but without success.


Solution

  • If you want to have a 24hr format in your TimePickerDialog you need to pass the correct value to constructor of TimePickerDialog. You can check the documentation of this class here. You can see that both of constructors accept boolean is24HourView flag with which we decide if we want our dialog in 24 hr format or not. If you want your app time to behave in the same way as your system, you can get system settings for 24hr format with this line: DateFormat.is24HourFormat(context) so you can just pass that value in your constructor.