How can I setMaxDate() for DatePicker to one month

2019-07-20 10:10发布

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

3条回答
forever°为你锁心
2楼-- · 2019-07-20 10:48
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
dialog.getDatePicker().setMaxDate(calendar.getTimeInMillis);

You can use "add" to add to the Calendar.MONTH

查看更多
祖国的老花朵
3楼-- · 2019-07-20 10:49

you have to override OnDateChangedListener `new OnDateChangedListener() {

            public void onDateChanged(DatePicker view, int year,
                    int month, int day) {
                Calendar newDate = Calendar.getInstance();
                newDate.add(Calendar.MONTH, 1);

                if (calendar.before(newDate)) {
                    view.init(minYear, minMonth, minDay, this);
                }
            }
        });`
查看更多
Anthone
4楼-- · 2019-07-20 10:54

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.

查看更多
登录 后发表回答