在 Android 日期选择器中将最大日期设置为 30 天

SetMax date to 30 days in Android Date Picker

我正在为 Datepicker 使用 Material 设计库。我需要设置最小和最大日期。最小日期有效,但我无法获得最大日期,该日期应该是从最小 date(current date) 算起的 30 天。谁能知道如何让它在这里工作?

public void show() {
    Calendar now = Calendar.getInstance();
    DatePickerDialog dpd = DatePickerDialog.newInstance(
            PostInfo.this,
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH)
    );
    dpd.setMinDate(Calendar.getInstance());

    Calendar calendar = Calendar.getInstance(); 
  calendar.add(Calendar.DAY_OF_MONTH, 30);   


    dpd.setMaxDate(calendar.getInstance());


    dpd.show(getFragmentManager(), "Datepickerdialog");

您可以使用setMaxDate()

DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);

Calendar calendar = Calendar.getInstance();  // this is default system date
                datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis());  //set min date                 // set today's date as min date
                calendar.add(Calendar.DAY_OF_MONTH, 30); // add date to 30 days later
                datePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis()); //set max date

所以这终于奏效了。我所要做的就是调用 dpd.setMaxDate(now) 而不是 dpd.setMaxDate(now.getInstance())

public void show() {
        Calendar now = Calendar.getInstance();

        DatePickerDialog dpd = DatePickerDialog.newInstance(
                PostInfo.this,
                now.get(Calendar.YEAR),
                now.get(Calendar.MONTH),
                now.get(Calendar.DAY_OF_MONTH)
        );

        dpd.setMinDate(Calendar.getInstance());
        now.add(Calendar.DAY_OF_MONTH, 30);

        dpd.setMaxDate(now);

        dpd.show(getFragmentManager(), "Datepickerdialog");

 }