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

半腔热情 提交于 2019-12-12 18:51:34

问题


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

回答1:


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.




回答2:


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:


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


来源:https://stackoverflow.com/questions/34545374/how-can-i-setmaxdate-for-datepicker-to-one-month-after-the-current-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!