AM/PM DateFormat substitution at TimePickerDialog

社会主义新天地 提交于 2020-01-05 08:03:55

问题


I have some layout/button and onClick I get TimePickerDialog with current time (previously defined from Calendar):

    RelativeLayout time = (RelativeLayout) findViewById(R.id.time_layout);
    time.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {
            TimePickerDialog dateDialog = new TimePickerDialog(SelectDateTimeActivity.this,
                    TimeSetListener,
                    hours, minutes, false);
            dateDialog.show();
        }
    });

TimePicker is in 12h mode - it has AM/PM mark. TimeSetListener looks like

private TimePickerDialog.OnTimeSetListener TimeSetListener = new TimePickerDialog.OnTimeSetListener() {
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        hours = hourOfDay;
        minutes = minute;
        updateTimeRow();
    }
};

and updateTimeRow() is

private void updateTimeRow() {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR, hours);
    c.set(Calendar.MINUTE, minutes);

    timeBody.setText("@ " + (String) (DateFormat.format("hh:mm aa", c.getTime())));
}

The problem is that time set in TimePickerDialog 06:00 PM (which really is 18:00, I checked via logging) I get 06:00 AM in my timeBody textView. If I set it to 06:00 AM (which really is 06:00) in timeBody textView I get 06:00 PM. Why?


回答1:


Use HOUR_OF_DAY in place of HOUR.

c.set(Calendar.HOUR, hours);

Replace it with:

c.set(Calendar.HOUR_OF_DAY, hours);


来源:https://stackoverflow.com/questions/7233249/am-pm-dateformat-substitution-at-timepickerdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!