Search code examples
javaandroiddatedatepickerandroid-datepicker

SetMax date to 30 days in Android Date Picker


I'm using a Material design library for Datepicker. I need to set min and max date. The min date works but I am not able to get the max date which should be 30 days from the min date(current date). Can anyone know how to make it work here?

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

Solution

  • So this finally worked. All I had to do is call dpd.setMaxDate(now) instead of 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");
    
     }