androidcalendartimepickertimepickerdialog

How to add an Extra zero in time for proper time format


I am using a timepicker to choose the time and then show it in a toast in 24 hour format. I am getting output in toast like "2:6" And I want to get it in proper time format like "02:06". How can I do that....

public void ShowTimePicker(View view) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");

}


public static class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();

        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

        Toast myToast = Toast.makeText(getContext(), hourOfDay + ":" + minute, Toast.LENGTH_SHORT);
        myToast.show();


    }
}                                      

Solution

  • First need to create one function that check your input and convert it in String as per condition.

    public String convertDate(int input) {
      if (input >= 10) {
        return String.valueOf(input);
      } else {
        return "0" + String.valueOf(input);
      }
    }
    

    Then you can call like this

    txtTime.setText(convertDate(hourOfDay) + ":" + convertDate(minute));
    

    And your Toast will be like this

    Toast myToast = Toast.makeText(getContext(), convertDate(hourOfDay) + ":" + convertDate(minute), Toast.LENGTH_SHORT);