Android:TimePicker设置setIs24HourView(true)无效,仍然是12小时制

最近在开发的过程中使用到了TimePicker,需求是可选择24小时制的时间日期,然后发现设置setIs24HourView(true)之后,再使用TimePicker的getCurrentHour得到的却是12小时制,也就是下午的时间,比如14点会显示为2点,那到底是什么原因呢?

小编在实现的过程中代码如下:

/**
     * 日期选择器弹窗
     * @param activity
     * @param textView
     */
    public static void showDatePickerDialog(Activity activity, final TextView textView) {
        Calendar calendar = Calendar.getInstance();

        new TimePickerDialog(activity, TimePickerDialog.THEME_HOLO_LIGHT, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = String.valueOf(hourOfDay);
                mMinute = String.valueOf(minute);
                if(hourOfDay < 10){
                    mHour = "0" + hourOfDay;
                }
                if(minute < 10){
                    mMinute = "0" + minute;
                }
                textView.setText(mYear + "-" + mMonth + "-" + mDay +" "+ mHour + ":" + mMinute + ":00");
            }
        }
                ,calendar.get(Calendar.HOUR)
                ,calendar.get(Calendar.MINUTE),true).show();

        new DatePickerDialog(activity, DatePickerDialog.THEME_HOLO_LIGHT,

                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        mYear = String.valueOf(year);
                        mMonth = String.valueOf(monthOfYear + 1);
                        mDay = String.valueOf(dayOfMonth);
                        if (monthOfYear < 9) {
                            mMonth = "0" + mMonth;
                        }
                        if (dayOfMonth < 10) {
                            mDay = "0" + mDay;
                        }
                    }
                }
                // 设置初始日期
                ,calendar.get(Calendar.YEAR)
                ,calendar.get(Calendar.MONTH)
                ,calendar.get(Calendar.DAY_OF_MONTH)).show();

    }

最后各方查阅终于得到答案,其实就是日期格式类型的问题:

代码中:

calendar.get(Calendar.HOUR)

修改为下面这两种方式实现都可以:

calendar.get(Calendar.HOUR_OF_DAY)

calendar.get(Calendar.getInstance().HOUR_OF_DAY)

当然,可能有些需求代码并不是这样实现的,但问题是一样的,比如下面这种:

TimePicker picker = (TimePicker) findViewById(R.id.timePicker1);
picker.setIs24HourView(true);
Calendar calendar = Calendar.getInstance();
picker.setCurrentHour(calendar.get(calendar.HOUR_OF_DAY));

这样问题就完美解决了!

希望可以帮助到开发中遇到此问题的,喜欢的可以点个关注哦,谢谢!

展开阅读全文

没有更多推荐了,返回首页