"Ready Android"
As stated in “Ready Android,” we need to convert the input time of 12 hours to 24 hours, then we must transfer this value to TimePicker, and finally, when we use the selected time, again we need to convert 24 hours of time in 12 hours, as shown in this code
String inputTime = "01:15 PM"
try {
DateFormat inputFormat = new SimpleDateFormat("hh:mm aa", Locale.US);
DateFormat outputFormat = new SimpleDateFormat("HH:mm", Locale.US);
Log.e("finalDate", outputFormat.format(inputFormat.parse(inputTime)));
inputTime = outputFormat.format(inputFormat.parse(inputTime));
inputHours = inputTime.substring(0, 2);
inputMinutes = inputTime.substring(3, 5);
Log.e("inputHours", inputHours);
Log.e("inputMinutes", inputMinutes);
} catch (ParseException e) {
e.printStackTrace();
}
TimePickerDialog mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String timeFormat;
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 finalSelectedHour, finalSelectedMinute;
if(selectedHour < 10)
finalSelectedHour = "0" + selectedHour;
else
finalSelectedHour = String.valueOf(selectedHour);
if (selectedMinute < 10)
finalSelectedMinute = "0" + selectedMinute;
else
finalSelectedMinute = String.valueOf(selectedMinute);
String selectedTime = finalSelectedHour + ":" + finalSelectedMinute + " " + timeFormat;
tvTime.setText(selectedTime);
}
}, Integer.parseInt(inputHours), Integer.parseInt(inputMinutes), false);
mTimePicker.setTitle("Select Time");
mTimePicker.show();
source
share