time picker showing time like 4:7 instead of 04:07

Tushar Narang picture Tushar Narang · Apr 2, 2014 · Viewed 14.5k times · Source

I have a time picker function which sets time in an EditText . But the format it shows is not suitable. for example for 04:07pm is shown as 4:7. whenever the digit in time is less than 10 it removes the 0 automatically. please help me out. My code is

        if (v == btnTimePicker1)
               {

                // Process to get Current Time
                final Calendar c = Calendar.getInstance();
                mHour = c.get(Calendar.HOUR_OF_DAY);
                mMinute = c.get(Calendar.MINUTE);

                // Launch Time Picker Dialog
                TimePickerDialog tpd = new TimePickerDialog(this,
                        new TimePickerDialog.OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay,
                                    int minute) {
                                // Display Selected time in textbox
                                txtTime1.setText(hourOfDay + ":" + minute);
                            }
                        }, mHour, mMinute, false);
                tpd.show();




            }

Answer

scottt picture scottt · Apr 2, 2014

Just change the line:

txtTime1.setText(hourOfDay + ":" + minute);

to:

txtTime1.setText(String.format("%02d:%02d", hourOfDay, minute));

and all will be well.

If you want a 12-hour clock instead of a 24-hour one, then replace that line with these instead:

int hour = hourOfDay % 12;
if (hour == 0)
    hour = 12;
txtTime1.setText(String.format("%02d:%02d %s", hour, minute, 
                               hourOfDay < 12 ? "am" : "pm"));

or you could do it in just 2 lines with:

int hour = hourOfDay % 12;    
txtTime1.setText(String.format("%02d:%02d %s", hour == 0 ? 12 : hour,
                               minute, hourOfDay < 12 ? "am" : "pm"));