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

前端 未结 8 1844
小蘑菇
小蘑菇 2021-02-05 05:41

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 l

相关标签:
8条回答
  • 2021-02-05 06:42

    The logic is simple, i have just trimmed the answers above

    just replace the line where we set time in editText with

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

    then add a function for it i.e

           public String pad(int input) 
             {
    
                String str = "";
    
                if (input > 10) {
    
                    str = Integer.toString(input);
                } else {
                    str = "0" + Integer.toString(input);
    
                }
                return str;
            }
    
    0 讨论(0)
  • You can use the following code -

      public void onTimeSet(TimePicker view, int hourOfDay, int minuteOfDay) {
       int hour;
       String minute, amOrPm;
       if (hourOfDay > 12) {
        hour = hourOfDay - 12;
        amOrPm= "PM";
       } else {
        hour = hourOfDay;
        amOrPm = "AM";
       }
       if(minuteOfDay < 10) {
          minute = "0"+minuteOfDay;
       } else {
          minute = "" + minuteOfDay;
       }
       txtTime1.setText(hour + " : " + minute + " " + amOrPm);
      }
    
    0 讨论(0)
提交回复
热议问题