问题
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