Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set minimum DatePicker date to current date

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?

like image 353
gsingh2011 Avatar asked Dec 01 '12 17:12

gsingh2011


People also ask

How do I set datepicker to current date?

To set current date in control to which jQuery UI datepicker bind, use setDate() method. Pass date object which needs to be set as an argument to setDate() method. If you want to set it to current date then you can pass 'today' as argument.

How do I restrict date in date picker?

You can restrict the users from selecting a date within the particular range by specifying MinDate and MaxDate properties. The default value of MinDate property is 1/1/1920 and MaxDate property is 12/31/2120 . Dates that appears outside the minimum and maximum date range will be disabled (blackout).


2 Answers

The error says you cannot set the minimum date to exactly now. Try subtracting a second:

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

From the source code the minimum date must be before, not equal to, the current date:

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

So you simply need to subtract enough time from now (System.currentTimeMillis()) pass date.before(mMinDate).

like image 154
Sam Avatar answered Sep 24 '22 12:09

Sam


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

datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());  
like image 39
Nikhil Jain Avatar answered Sep 24 '22 12:09

Nikhil Jain