我想将用户在DatePicker中选择的最短日期设置为当前日期。我试过这个:
DatePicker datePicker = (DatePicker) findViewById(R.id.event_date);
datePicker.setMinDate(System.currentTimeMillis());
这给了我以下例外:
12-01 12:23:31.226: E/AndroidRuntime(10311): Caused by: java.lang.IllegalArgumentException: fromDate: Sat Dec 01 12:23:31 EST 2012 does not precede toDate: Sat Dec 01 12:23:31 EST 2012
我该怎么做?
答案 0 :(得分:148)
错误表示您现在无法将最小日期设置为 。尝试减去第二个:
datePicker.setMinDate(System.currentTimeMillis() - 1000);
从源代码开始,最小日期必须在当前日期之前,而不是等于:
if (date.before(mMinDate)) {
throw new IllegalArgumentException("fromDate: " + mMinDate.getTime()
+ " does not precede toDate: " + date.getTime());
}
所以你只需要从现在开始减去足够的时间(System.currentTimeMillis()
)传递date.before(mMinDate)
。
答案 1 :(得分:12)
如果您不想使用自定义对话框。使用此单行代码:
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
答案 2 :(得分:8)
这对我来说非常有效。简单又好。
DatePickerDialog dialog = new DatePickerDialog(this, this,
Calendar.YEAR,Calendar.MONTH,
Calendar.DAY_OF_MONTH);
dialog.getDatePicker().setMinDate(Calendar.getInstance().getTimeInMillis());
dialog.show();
答案 3 :(得分:7)
检查Android DatePickerDialog 设置最小和最大日期代码。
这是examples。
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(getActivity(),AlertDialog.THEME_TRADITIONAL,this,year, month, day);
//Get the DatePicker instance from DatePickerDialog
DatePicker dp = dpd.getDatePicker();
//Set the DatePicker minimum date selection to current date
dp.setMinDate(c.getTimeInMillis());//get the current day
//dp.setMinDate(System.currentTimeMillis() - 1000);// Alternate way to get the current day
//Add 6 days with current date
c.add(Calendar.DAY_OF_MONTH,6);
//Set the maximum date to select from DatePickerDialog
dp.setMaxDate(c.getTimeInMillis());
//Now DatePickerDialog have 7 days range to get selection any one from those dates
答案 4 :(得分:4)
将此行添加到DatePicker片段会将最小日期设置为当前日期&禁用前几个月。
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
答案 5 :(得分:0)
这可以帮到你。
Calendar cal=Calendar.getInstance();
int year=cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int day=cal.get(Calendar.DAY_OF_MONTH);
int hour=cal.get(Calendar.HOUR_OF_DAY);
int min=cal.get(Calendar.MINUTE);
datePicker.updateDate(year, month, day);
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(min);
答案 6 :(得分:0)
试试这个
datePicker.setMinDate(new GregorianCalendar.getTimeInMillis());
答案 7 :(得分:0)
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
OR
DatePickerDialog dialog = new DatePickerDialog(this, this,
Calendar.YEAR,Calendar.MONTH,
Calendar.DAY_OF_MONTH);
dialog.getDatePicker().setMinDate(Calendar.getInstance().getTimeInMillis());
dialog.show();
答案 8 :(得分:0)
datePicker.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
最小日期不能是瞬间