Bahu Bahu - 1 year ago 94
Android Question

Not able to select AM/PM dynamically in TimePickerDialog

I had time in TextView like

10:53 PM
. When clicking on that TextView i'm showing the TextView time on
but i'm unable to show the AM/PM according to the TextView. For this requirement i saw link1, link2, link3 and many more but nothing was worked for me. Any one know about this

My code

String inputTime = "10:53 PM", inputHours, inputMinutes;

inputHours = inputTime.substring(0, 2);
inputMinutes = inputTime.substring(3, 5);

tvTime.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

TimePickerDialog mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {

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

String selectedTime = selectedHour + ":" + selectedMinute + " " + timeFormat;


}, Integer.parseInt(inputHours), Integer.parseInt(inputMinutes), false);//mention true for 24 hour's time format
mTimePicker.setTitle("Select Time");;


It always selecting the AM instead of PM as shown image
enter image description here

Answer Source

You don't need to get am/pm value cause hour will be always in 24h format. Timepicker display ap/pm but return 24h format value.

here hourOfDay will always be 24-hour. If you opened the dialog with is24HourView set to false, the user will not have to deal with 24-hour formatted times, but Android will convert that to a 24-hour time when it calls onTimeSet().

    Calendar calendar = Calendar.getInstance();
            TimePickerDialog timePickerDialogfrom = new TimePickerDialog(activity, new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calendar.set(Calendar.MINUTE, minute);
//Conversion for AM/PM as you are doing
        }, calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE), false);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download