user2274349
user2274349

Reputation: 415

Display AM and PM in the EditText from TimePickerDialog

Halo, how can I make timePickerDialog display on EditText with AM and PM? after timePickerDialog set, there is 24hour format. For example, 7.45pm, the EditText will get 19.45 that's all. I want it to be 7.45 pm in the EditText. Somebody can help?

Here is my coding...

private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
    public void onTimeSet(TimePicker view, int selectedHour,
            int selectedMinute) {
        hour = selectedHour;
        minute = selectedMinute;
        String zone = "";

        if (Calendar.AM_PM == Calendar.AM)              
            zone = "AM";

        else if (Calendar.AM_PM == Calendar.PM)         
            zone = "PM";

        // set current time into textview
        timeField.setText(new StringBuilder().append(pad(hour)).append(":").append(pad(minute)).append(" ").append(zone));

    }

};

private static String pad(int c) {
    if (c >= 10)
       return String.valueOf(c);
    else
       return "0" + String.valueOf(c);
}

Upvotes: 1

Views: 700

Answers (1)

Sam
Sam

Reputation: 86948

For example, 7.45pm, the EditText will get 19.45 that's all. I want it to be 7.45 pm in the EditText.

The simple answer is to check if selectHour is greater than 12:

if(selectedHour > 12) {
    selectedHour -= 12;
    zone = "PM";
}
else 
    zone = "AM";

You could also use built-in time objects, like Calendar, and SimpleDateFormat to display whatever format you want.

Upvotes: 2

Related Questions