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 less than 10 it removes the 0 automatically. please help me out. My code is
if (v == btnTimePicker1) { // Process to get Current Time final Calendar c = Calendar.getInstance(); mHour = c.get(Calendar.HOUR_OF_DAY); mMinute = c.get(Calendar.MINUTE); // Launch Time Picker Dialog TimePickerDialog tpd = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // Display Selected time in textbox txtTime1.setText(hourOfDay + ":" + minute); } }, mHour, mMinute, false); tpd.show(); }
Android App Development for Beginners Android Time Picker allows you to select the time of day in either 24 hour or AM/PM mode. The time consists of hours, minutes and clock format. Android provides this functionality through TimePicker class.
is24HourView(): This method is used to check the current mode of the time picker. This method returns true if its 24 hour mode or false if AM/PM mode is set.
Time pickers allow users to enter a specific time value. They can be used for a wide range of scenarios. Common use cases include: Setting an alarm. Scheduling a meeting.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With