How to load my DatePickerDialog in Android 24-hour format?

0

How can I improve the following code that I will share so that when I click on a button I will load the DatePickerDialog in 24 hours format if or yes, since at the moment it loads me in the format that the user has configured in his system, either 12 hours or 24 hours.

  

Here I share the code

public void obtenerHora(){

    final Calendar c = Calendar.getInstance();
    final int hour = c.get(Calendar.HOUR_OF_DAY);
    final int minute = c.get(Calendar.MINUTE);
    final int am_pm = c.get(Calendar.AM_PM);


    TimePickerDialog recogerHora = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            //mEtHora: es un edit text que almacenara la hora seleccionada por el usuario
        mEtHora.setText(hourOfDay + ":" + minute);

        }
    }, hour, minute, false);


    recogerHora.show();

}
  

In some help I have seen that they use setIs24HourView (true) , but as long as it is a TimePicker embedded in the layout.

    
asked by Luis Rene Mas Mas 31.08.2017 в 20:00
source

1 answer

3

Use the setIs24HourView(boolean) method by passing it to you true and force to 24 hours:

recogerHora.setIs24HourView(true);
recogerHora.show();

As you use TimePickerDialog , in the constructor you can specify it to use the format 24 hours:

new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int i, int i1) {

            }
        }, Calendar.getInstance().get(Calendar.HOUR_OF_DAY), Calendar.getInstance().get(Calendar.MINUTE), true);

Notice that the last parameter is where you indicate if you use the format 24 hours.

Then in your case just change the last parameter to true:

public void obtenerHora(){

final Calendar c = Calendar.getInstance();
final int hour = c.get(Calendar.HOUR_OF_DAY);
final int minute = c.get(Calendar.MINUTE);
final int am_pm = c.get(Calendar.AM_PM);

// que utilize formato de 24 horas
boolean formato24Horas = true;

TimePickerDialog recogerHora = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

        //mEtHora: es un edit text que almacenara la hora seleccionada por el usuario
    mEtHora.setText(hourOfDay + ":" + minute);

    }
}, hour, minute, formato24Horas );


recogerHora.show();

}
    
answered by 31.08.2017 / 20:06
source