24

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




            }
Tushar Narang
  • 1,997
  • 3
  • 21
  • 49

9 Answers9

71

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"));
scottt
  • 8,301
  • 1
  • 31
  • 41
  • 2
    This answer should be accepted one Because String.format("%02d:%02d", hourOfDay, minute) make sense instead of if checks – Swap-IOS-Android Feb 25 '15 at 10:20
  • Could you explain what the regex expression mean? – most venerable sir Oct 19 '18 at 16:47
  • No regex is used. If you're referring to the "%02d:%02d %s", that's a String format. In those, each "%02d" indicates a replacement parameter that will be a 2-digit number with leading zeros, while the "%s" indicates a replacement string. So the first "%02d" will display the hours as 2 digits, the next one will display the minutes as 2 digits, and the %s will display either "am" or "pm". The docs can be found here: https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html . – scottt Oct 19 '18 at 20:17
  • 1
    Thank you so much for the solution, saved much of my time! – hetsgandhi Jul 13 '19 at 06:57
5

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;
        }
Tushar Narang
  • 1,997
  • 3
  • 21
  • 49
4

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);
    }
W3hri
  • 1,563
  • 2
  • 18
  • 31
3

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

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

Then you can call like this

 txtTime1.setText(pad(hourOfDay) + ":" + pad(minute));
Chirag Ghori
  • 4,231
  • 2
  • 20
  • 35
2

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);
  }
crazyPixel
  • 2,301
  • 5
  • 24
  • 48
0
TimePickerDialog tpd = new TimePickerDialog(YourActivity.this, new 
TimePickerDialog.OnTimeSetListener() {

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        if (hourOfDay == 0) {
            hourOfDay = 12;
        }
        mEndTime = (String.format("%02d:%02d", hourOfDay, minute));
        //mEndTime = (hourOfDay + ":" + minute);

        mEditTextEnd.setText(mEndDate + " " + mEndTime + ":00");
    }
}, mHourEnd, mMinuteEnd, true);
tpd.show();
Pang
  • 9,564
  • 146
  • 81
  • 122
Ashwin H
  • 695
  • 7
  • 24
0

Try this

simpleTimePicker1 = (TimePicker) findViewById(R.id.timedawn);
simpleTimePicker1.setIs24HourView(true);
simpleTimePicker1.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay1, int minute1 ) {

        String shour1 = String.valueOf(hourOfDay1);
        String sminute1 = String.valueOf(minute1);


        if ((shour1.length() == 1 ) && (sminute1.length() == 1)) {
            sHour1= "0" + shour1;
            sMinute1= "0" + sminute1;
        }
        else if ((shour1.length() == 2 ) && (sminute1.length() == 1)) {
            sHour1= shour1;
            sMinute1= "0" + sminute1;
        }
        else if ((shour1.length() == 1 ) && (sminute1.length() == 2)) {
            sHour1= "0" + shour1;
            sMinute1= sminute1;
        }
        else{
            sHour1= shour1;
            sMinute1= sminute1;
        }
        String timew = sHour1+":" + sMinute1;
        time3=timew;
    }

});
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Jimbee
  • 13
  • 5
0

i might be little late to the party but this will surely help to someone else.

 private String getTime(int hr, int min) {
    Time tme = new Time(hr, min, 0);//seconds by default set to zero
    Format formatter;
    formatter = new SimpleDateFormat("h:mm a");
    return formatter.format(tme);
}
0

I had the same problem. TimePicker simply didn't want to display the time in the form 09:01. Maybe the solution for others too. I created a method that checks the time. setTime is called by the onTimeChanged event

It is checked whether the hour or minute is less than 10. If so, then a 0 was placed to the left of the hour or minute.

Best regards Chris

public void _setTime(final double _nHour, final double _nMinute) {
    if (_nHour < 10) {
        strStd = "0".concat(String.valueOf((long)(_nHour)));
    }
    else {
        strStd = String.valueOf((long)(_nHour));
    }
    if (_nMinute < 10) {
        strMin = "0".concat(String.valueOf((long)(_nMinute)));
    }
    else {
        strMin = String.valueOf((long)(_nMinute));
    }
    edittext_Start.setText(strStd.concat(".".concat(strMin)));
}
Chris Pohl
  • 11
  • 3