我得到24小时格式的时间选择器值。如何将其转换为12小时格式?

时间:2017-12-06 10:08:00

标签: android datetimepicker timepicker

代码

    public static class TimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR);
            int minute = c.get(Calendar.MINUTE);
            return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
        }
        @Override
        public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
//            displayCurrentTime.setText(String.valueOf(hourOfDay) + " : " + String.valueOf(minute));
            displayCurrentTime.setText(String.format("%02d:%02d %s", hourOfDay == 0 ? 12 : hourOfDay,
                    minute, hourOfDay < 12 ? "am" : "pm"));
        }
    }

这是我用来显示时间选择器的时间的代码。但由于24hr format,时间显示在is24HourFormat
如何将其转换为12hr format

3 个答案:

答案 0 :(得分:0)

使用SimpleDateFormate

  @Override
public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
    Calendar calendar=Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY,hourOfDay);
    calendar.set(Calendar.MINUTE,minute);
    String dateIn12Hour=new SimpleDateFormat("hh:mm a").format(calendar.getTimeInMillis());
    displayCurrentTime.setText(dateIn12Hour);
}

答案 1 :(得分:0)

使用setIs24HourView的{​​{1}}方法并将其设置为false。

https://developer.android.com/reference/android/widget/TimePicker.html#setIs24HourView(java.lang.Boolean)

答案 2 :(得分:0)

你可以通过 -

来做到
Calendar mcurrentTime = Calendar.getInstance();
        int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
        int minute = mcurrentTime.get(Calendar.MINUTE);
        TimePickerDialog mTimePicker;
        mTimePicker = new TimePickerDialog(AddReminder.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                eReminderTime.setText( selectedHour + ":" + selectedMinute);
            }
        }, hour, minute, true);//Yes 24 hour time  //false if 12 hour
        mTimePicker.setTitle("Select Time");
        mTimePicker.show();

    }
});