Datepicker: How to popup datepicker when click on button and store value in variable

Ashish Patil picture Ashish Patil · Sep 25, 2013 · Viewed 47.2k times · Source

I want to show datepicker popup window. I have found some examples but i am not getting it properly. I have one button and i want that when i click on button the datepicker dialog should popup and after setting the date, the date should be stored in a variable. PLease provide me sample code or good links.

Answer

Gowri picture Gowri · Sep 25, 2013

Try this.

Use this code in your button click. The date picker dialog will be shown.

            Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);
    System.out.println("the selected " + mDay);
    DatePickerDialog dialog = new DatePickerDialog(Registration.this,
            new mDateSetListener(), mYear, mMonth, mDay);
    dialog.show();

Then, mDateSetListener class needs to be written.

class mDateSetListener implements DatePickerDialog.OnDateSetListener {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            // getCalender();
            int mYear = year;
            int mMonth = monthOfYear;
            int mDay = dayOfMonth;
            v.setText(new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("/").append(mDay).append("/")
                    .append(mYear).append(" "));
            System.out.println(v.getText().toString());


        }
    }

Please check this answer and vote.