0

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(), "%02d:%02d", 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();
HeroreH29
  • 79
  • 8

3 Answers3

1
  @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);
}
Rudra Rokaya
  • 637
  • 1
  • 5
  • 9
  • This code is not directly linked to my code but the logic using `SimpleDateFormat` in your code, answered my question. Thank you! – HeroreH29 Nov 20 '21 at 16:21
1

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 )
)
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You have to replace true instead of false and you're done

final Calendar c = Calendar.getInstance();
        int mHour = c.get(Calendar.HOUR_OF_DAY);
        int mMinute = c.get(Calendar.MINUTE);

        TimePickerDialog.OnTimeSetListener onTimeSetListener = (timePicker, selectedHour, selectedMinute) -> {
            int hour = selectedHour;
            int minute = selectedMinute;
            String time = String.format(Locale.getDefault(), "%02d:%02d", hour, minute);
            electionsText.setText("Registrations Will End On:\n" + date + "\n@ " + time);
        };


        TimePickerDialog timePickerDialog = new TimePickerDialog(this, onTimeSetListener, mHour, mMinute, true);

        timePickerDialog.setTitle("Select Time");
        timePickerDialog.show();