Show the time picker in hh:mm format

Steve picture Steve · Sep 1, 2015 · Viewed 7.8k times · Source

I have to show the time picker in hh:mm format on Click the edit text.So that I had used the below code.

MainActivity.java:

  e6.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                    // TODO Auto-generated method stub
                    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
                    Calendar mcurrentTime = Calendar.getInstance();
                    int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
                    int minute = mcurrentTime.get(Calendar.MINUTE);
                    TimePickerDialog mTimePicker;
                    mTimePicker = new TimePickerDialog(AddFlight.this, new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                            e6.setText(selectedHour + ":" + selectedMinute);

                        }
                    }, hour, minute, true);//Yes 24 hour time
                    mTimePicker.setTitle("Select Time");
                    mTimePicker.show();

            }
        });

It is working well and shows the time picker.But my issue is,when I select the 04:15 in timepicker, it display 4:15.It doesn't include 0 before 4.I need to show the timepicker in hh:mm format.

Anyone can help me with this.Thank you.

Answer

Steve picture Steve · Sep 1, 2015

Just now I had referred this post and change the single line:

this line

e6.setText(selectedHour + ":" + selectedMinute);

to

e6.setText(String.format("%02d:%02d", selectedHour, selectedMinute));