DatePicker

suggest change

DatePicker lets the user pick a date. A new DatePicker can take an initial date. If you do not set one, it starts on the current date.

We can show DatePicker to user by using DatePickerDialog or by creating our own layout with DatePicker widget.


Also we can limit range of date, which user can pick.

By setting minimum date in milliseconds

//In this case user can pick date only from future
datePicker.setMinDate(System.currentTimeMillis());

By setting maximum date in milliseconds

// The user can pick a date only up to seven days from now.
datePicker.setMaxDate(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(7));

To receive the date the user picked, use a listener.

If we are using DatePickerDialog, we can set OnDateSetListener in constructor when we are creating new instance of DatePickerDialog:

Sample use of DatePickerDialog

public class SampleActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }

    private void showDatePicker() {
        //We need calendar to set current date as initial date in DatePickerDialog.
        Calendar calendar = new GregorianCalendar(Locale.getDefault());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, this, year, month, day);
        datePickerDialog.show();
    }

    @Override
    public void onDateSet(DatePicker datePicker, int year, int month, int day) {

    }
}

Otherwise, if we are creating our own layout with DatePicker widget, we also have to create our own listener as it was shown in other example

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents