Search code examples
androiddatepickerdialog

Get current date on Date Picker Dialog


I want to get current date on Date Picker Dialog when user click but it is not working. My default date is not changing to my current date. What am I doing wrong in my code?

            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();

Solution

  • You are passing the values in wrong order. You need to pass values in this order:

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

    Change it like this:

    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 comes first than month and day in the last.