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

前端 未结 8 1840
小蘑菇
小蘑菇 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:40

    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"));
    

提交回复
热议问题