Show TimePicker with 12 or 24 hour format in android

Sergio76 picture Sergio76 · Nov 15, 2013 · Viewed 15.2k times · Source

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.

Answer

bourax webmaster picture bourax webmaster · Nov 15, 2013

f you want the TimePicker to be correctly initialized with the current time in 24h format use the following:

import java.util.Calendar;

timePicker.setIs24HourView(true);
timePicker.setCurrentHour(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));

Otherwise, due to Android bug, the picker will start with an incorrect hour (2 instead of 14 etc). hope this helps