OBX
OBX

Reputation: 6114

TimePicker to setText, simple bug

After picking a time from a TimePicker I am displaying that using setText() , however , so far everything works well, however the problem is , if I choose 05:09 , I only get displayed 5:9 PM in TextView. I miss the preceding zeros. But I require that

Here is the Code I use :

public void onTimeSet(TimePicker timePicker,int selectedHour, int selectedMinute) 
{
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, selectedHour);
    calendar.set(Calendar.MINUTE, selectedMinute);

    int c_hour,c_min;
    String format;
    c_hour=selectedHour;
    c_min=selectedMinute;

    if (c_hour == 0) {
          c_hour += 12;
          format = "AM";
    } 
    else if (c_hour == 12) {
          format = "PM";
    } 
    else if (c_hour > 12) {
          c_hour -= 12;
          format = "PM";
    } 
    else {
         format = "AM";
    }

TextView dimple = (TextView)findViewById(R.id.timeText);
dimple.setText(new StringBuilder().
            append(c_hour).append(" : ").append(c_min).append(" ").append(format));

What is the quick way to fix it ?

Upvotes: 0

Views: 93

Answers (3)

Krishna V
Krishna V

Reputation: 1821

You can get the time, by prefixing zeros.

String formatTime=String.format("%02d : %02d", hour, minute);

or

Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, hour);
        cal.set(Calendar.MINUTE, minute);
        String formatTime = new SimpleDateFormat("hh:mm a").format(cal.getTime());

Upvotes: 5

Megh Vidani
Megh Vidani

Reputation: 635

You can use SimpleDateFormat for constructing time string as mentioned here:

Convert java.util.Date to String

In your case you can use "HH:mm a" as the format.

So your sample code should look like:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, selectedHour);
calendar.set(Calendar.MINUTE, selectedMinute);

DateFormat dateFormat = new SimpleDateFormat("HH:mm a");

Date dateValue = calendar.getTime();
String requiredTime = dateFormat.format(dateValue);
TextView dimple = (TextView)findViewById(R.id.timeText);
dimple.setText(requiredTime);

Hope it helps :)

Upvotes: 1

2red13
2red13

Reputation: 11227

String str_hour = c_hour<10 ? "0"+String.valueOf(c_hour):String.valueOf(c_hour);   

String str_min = c_min<10 ? "0"+String.valueOf(c_min):String.valueOf(c_min);  

Upvotes: 0

Related Questions