time picker showing time like 4:7 instead of 04:07
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"));
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;
}
You can check if the hours and minutes are less then ten. If so, you just add a "0" infront of that specific string. Just modify your code like this:
@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
String hourString;
if (hourOfDay < 10)
hourString = "0" + hourOfDay;
else
hourString = "" +hourOfDay;
String minuteSting;
if (minute < 10)
minuteSting = "0" + minute;
else
minuteSting = "" +minute;
txtTime1.setText(hourString + ":" + minuteSting);
}