获取日期选择器对话框的当前日期

时间:2015-05-08 05:20:24

标签: android datepickerdialog

我想在用户点击时获取日期选择器对话框的当前日期,但它不起作用。我的默认日期未更改为当前日期。我的代码中我做错了什么?

            Calendar mcurrentDate = Calendar.getInstance();

            int day   = mcurrentDate.get(Calendar.DAY_OF_MONTH);
            int month = mcurrentDate.get(Calendar.MONTH);
            int year  = mcurrentDate.get(Calendar.YEAR);

            DatePickerDialog dpd;
            dpd = new DatePickerDialog(getActivity(), 0,
                    new DatePickerDialog.OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year,
                                int month, int day) {
                            // TODO Auto-generated method stub
                            dateTxtVu.setText("Date: " + day + "-" + month
                                    + "-" + year);
                            dateStr = day + "-" + month + "-" + year;
                        }

                    }, day, month, year);
            dpd.show();

1 个答案:

答案 0 :(得分:5)

您正在以错误的顺序传递值。您需要按以下顺序传递值:

public DatePickerDialog(Context context, int theme, OnDateSetListener listener, int year,
        int monthOfYear, int dayOfMonth)

像这样改变:

Calendar mcurrentDate = Calendar.getInstance();

        int day   = mcurrentDate.get(Calendar.DAY_OF_MONTH);
        int month = mcurrentDate.get(Calendar.MONTH);
        int year  = mcurrentDate.get(Calendar.YEAR);

        DatePickerDialog dpd;
        dpd = new DatePickerDialog(getActivity(), 0,
                new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year,
                            int month, int day) {
                        // TODO Auto-generated method stub
                        dateTxtVu.setText("Date: " + day + "-" + month
                                + "-" + year);
                        dateStr = day + "-" + month + "-" + year;
                    }

                }, year, month, day);
        dpd.show();

year优先于monthday