Bahu Bahu - 12 days ago 5
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
TimePickerDialog
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() {
@Override
public void onClick(View v) {


TimePickerDialog mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
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;

tvTime.setText(selectedTime);

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

}
});


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

Answer

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() {
            @Override
            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);
Comments