如何设置日期选择器的最大和最小限制?

How to set maximum & minimum limits to date picker?

我有好几次在我的应用程序中使用日期选择器。我希望我的日期选择器显示符合某些限制的日期。我正在使用以下代码:-

@Override
    protected Dialog onCreateDialog(int id) {
        switch(id) {
            case DATE_PICKER_DIALOG:
                datePickerDialogDateSetListener = new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDate) {
                        year = selectedYear;
                        month = selectedMonth;
                        date = selectedDate;

                        activitySignUpDateEditText.setText(new StringBuilder().append(date));
                        activitySignUpMonthEditText.setText(new StringBuilder().append(month + 1));
                        activitySignUpYearEditText.setText(new StringBuilder().append(year));
                    }
                };

                return new DatePickerDialog(this, datePickerDialogDateSetListener, year, month, date);

            default:
                return null;
        }
    } 

我希望日期选择器在某处显示当前日期 18 年前的最大日期,并将最小日期显示为当前日期。我搜索了很多但没有找到任何满意的答案。我知道日期选择器的 setMaxDate() 和 setMinDate() 方法,但是当我尝试使用它时,我无法在我的编辑文本上设置选定的日期。任何帮助将不胜感激。提前致谢。

您可以尝试替换此行:

return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);

通过那些:

DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
DatePicker datePicker = dpDialog.getDatePicker();

Calendar calendar = Calendar.getInstance();//get the current day
datePicker.setMaxDate(calendar.getTimeInMillis());//set the current day as the max date
return dpDialog;

与您设置最短日期的方式相同

DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
DatePicker datePicker = dpDialog.getDatePicker();

Calendar calendar = Calendar.getInstance();//get the current day
datePicker.setMinDate(calendar.getTimeInMillis());//set the current day as the max date
return dpDialog;

要将最大日期设置为 18 年前,以下代码片段即可完成此工作:

Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dateDialog = new DatePickerDialog(this, datePickerListener, year - 18, month, day);

//For setting minimum date as Current Date
//dateDialog.getDatePicker().setMinDate(c.getTimeInMillis ());

//For setting maximum date as 18 years back
c.set(year - 18, month, day);
dateDialog.getDatePicker().setMaxDate(c.getTimeInMillis());
return dateDialog;

由于MaxDate不能小于MinDate,因此当MaxDate设置为18年前时,MinDate不应设置为当前日期。

希望对你有用。