Search code examples
javaandroidtimepicker

How to format time from Android's TimePicker?


Hi I am currently using a TimePickerDialog to set the time and display it into a text view. However, I am having problems with the formating. This is my code

    TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() {
    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        if ((hourOfDay >= 1) && (hourOfDay <= 11.59)) {
            hours = hourOfDay;
            am_pm = "AM";
        } else if (hourOfDay >= 12) {
            hours = hourOfDay - 12;
            am_pm = "PM";
        } else if (hourOfDay == 0) {
            hours = 12;
            am_pm = "AM";
        }

        tvScheduleTime.setText(hours + " : " + minute + " " + am_pm);

    }
};

This method works in retrieving AM and PM but the numbering is weird, like 6:08 AM becomes 6:8 AM. How can I make it so that it creates the text HH-MM AM/PM?


Solution

  • In this case add this line before print

      if(hours <10) hours ="0"+ hours;
      if(minute<10)minute="0"+minute;