I followed a short YouTube tutorial about TimePickerDialog. Since the video is short, it does not show how to display selected time in a 12-hour format. I want to know how to display it to 12-hour format with PM and AM at the side of the selected time.
This is the code I followed from YT:
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
int hour = selectedHour;
int minute = selectedMinute;
String time = String.format(Locale.getDefault(), "d:d", hour, minute);
electionsText.setText("Registrations Will End On:\n" date "\n@ " time);
}
};
int style = AlertDialog.THEME_HOLO_LIGHT;
TimePickerDialog timePickerDialog = new TimePickerDialog(this, style, onTimeSetListener, hour, minute, false);
timePickerDialog.setTitle("Select Time");
timePickerDialog.show();
CodePudding user response:
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("KK:mm a");
String currentTime = simpleDateFormat.format(c.getTime());
dateTimeSharedViewModel.setTime(currentTime);
}
CodePudding user response:
java.time
Use the modern java.time classes defined in JSR 310 that years ago supplanted the terrible legacy classes Calendar
, Date
, SimpleDateFormat
.
Generally best to let java.time automatically localize rather than hard-code a format.
LocalTime
.of( hour , minute )
.format(
DateTimeFormatter
.ofLocalizedTime( FormatStyle.SHORT )
.withLocale( Locale.US )
)