Search code examples
javaandroiddatepickerandroid-datepickerandroid-date

How can I setMaxDate() for DatePicker to one month after the current date?


Here's my onCreateDialog:

DatePickerDialog dialog = new DatePickerDialog(this, dpickerListener, year_x, month_x, day_x);
        dialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        dialog.getDatePicker().setMaxDate();

As you can see, setMaxDate() is empty. I want to set the max date of the datePickerDialog to one month after the current date. Here's how I get the current date:

cal2 = Calendar.getInstance();
    currentDay = cal2.get(Calendar.DAY_OF_MONTH);
    currentMonth = cal2.get(Calendar.MONTH);
    currentYear = cal2.get(Calendar.YEAR);
    currentDate = new Date();
    currentDate.setDate(currentDay);
    currentDate.setMonth(currentMonth);
    currentDate.setYear(currentYear);

Solution

  • Use this snippet

    Calendar cal=Calendar.getInstance()
    cal.add(Calendar.MONTH,1)
    long afterTwoMonthsinMilli=cal.getTimeInMillis()
        DatePickerDialog.getDatePicker().setMaxDate(afterTwoMonthsinMilli);
    

    It reads the current system date into a calendar object and adds 1 to the specified field,In this case MONTH and returns a calendar object

    Similarly if you want to add values to other fields,Specify the field in the field type as:

    • Calendar.DAY_OF_MONTH
    • Calendar.YEAR
    • Calendar.HOUR

    etc.