How to set minimum DatePicker date to current date

2020-01-24 20:45发布

I want to set the minimum date the user can choose in a DatePicker to the current date. I've tried this:

DatePicker datePicker = (DatePicker) findViewById(R.id.event_date);
datePicker.setMinDate(System.currentTimeMillis());

That gives me the following exception:

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

How do I do this?

8条回答
时光不老,我们不散
2楼-- · 2020-01-24 21:03

This worked perfectly for me. easy and nice.

DatePickerDialog dialog = new DatePickerDialog(this, this,
              Calendar.YEAR,Calendar.MONTH,
                Calendar.DAY_OF_MONTH);

        dialog.getDatePicker().setMinDate(Calendar.getInstance().getTimeInMillis());
        dialog.show();
查看更多
地球回转人心会变
3楼-- · 2020-01-24 21:04

This can help you.

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);
查看更多
倾城 Initia
4楼-- · 2020-01-24 21:06

If you don't want to use a custom dialog. Use this single line code:

datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()); 
查看更多
【Aperson】
5楼-- · 2020-01-24 21:11

Adding this line to your DatePicker Fragment will set the minimum date as current date & disable the previous months.

datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
查看更多
兄弟一词,经得起流年.
6楼-- · 2020-01-24 21:15

Check the Android DatePickerDialog set minimum and maximum date code.

Here is the 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 
查看更多
▲ chillily
7楼-- · 2020-01-24 21:15

Try this

datePicker.setMinDate(new GregorianCalendar.getTimeInMillis());
查看更多
登录 后发表回答