如何将最小DatePickerdate设置为当前date

我想设置用户可以select在DatePicker到当前date的最小date。 我试过这个:

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 

我该怎么做呢?

错误表示您不能将最小date设置为现在。 尝试减去第二个:

 datePicker.setMinDate(System.currentTimeMillis() - 1000); 

从源代码中,最小date必须在当前date之前,不等于当前date:

 if (date.before(mMinDate)) { throw new IllegalArgumentException("fromDate: " + mMinDate.getTime() + " does not precede toDate: " + date.getTime()); } 

所以你只需要从现在开始减去足够的时间( System.currentTimeMillis() )传递date.before(mMinDate)

如果你不想使用自定义对话框。 使用这个单行代码:

 datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()); 

检查Android DatePickerDialog设置的最小最大date代码。

这里是例子 。

 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 

尝试这个

 datePicker.setMinDate(new GregorianCalendar.getTimeInMillis()); 

。datePickerDialog.getDatePicker()setMinDate(System.currentTimeMillis的()); 将此行添加到DatePicker Fragment将设置最短date为当前date并禁用前几个月。

这可以帮助你。

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