Skip to content Skip to sidebar Skip to footer

Time Picker Showing Time Like 4:7 Instead Of 04:07

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

Solution 1:

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:

inthour= 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:

inthour= hourOfDay %12;    
txtTime1.setText(String.format("%02d:%02d %s", hour==0 ? 12 : hour,
                               minute, hourOfDay <12 ? "am" : "pm"));

Solution 2:

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(intinput) 
         {

            String str = "";

            if (input > 10) {

                str = Integer.toString(input);
            } else {
                str = "0" + Integer.toString(input);

            }
            returnstr;
        }

Solution 3:

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:

@OverridepublicvoidonTimeSet(TimePicker view, int hourOfDay,
    int minute) {
        // Display Selected time in textboxString 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);
    }

Solution 4:

First need to create one function that check your input and convert it in String as per condition.

publicStringpad(int input) {
    if (input >= 10) {
        returnString.valueOf(input);
    } else {
        return"0" + String.valueOf(input);
    }
}

Then you can call like this

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

Solution 5:

You can use the following code -

publicvoidonTimeSet(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);
  }

Post a Comment for "Time Picker Showing Time Like 4:7 Instead Of 04:07"