How to allow user to select date only up to 10 years from today from datepicker in Android?

I am stuck at the point where I need to ask for the date of birth from the user as input. I need to restrict so that the user cannot add the date before 10 years).

+3


source to share


3 answers


I think you mean that users cannot add a date earlier than 10 years before? Or are your users mostly children between the ages of 10 and 0?

Since your date limit is based on the current date, you need to set the limit programmatically with setMinDate(long date)

and setMaxDate(long date)

. As you can see, this method works with the date in milliseconds, so you need to laugh in milliseconds first:

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -10);                //Goes 10 Year Back in time ^^
long upperLimit = calendar.getTimeInMillis();    //Get date in millisecond (epoch)

      



and then set the limit using the method above:

datePicker.setMaxDate(upperLimit);

      

+2


source


You can do it:

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

      



More information: fooobar.com/questions/187827 / ...

0


source


try this code in datePicker dialog:

    Calendar c = Calendar.getInstance();
    c.add(Calendar.YEAR, -10);
    long tenYearBack = c.getTimeInMillis();
    datePickerDialog.getDatePicker().setMinDate(tenYearBack);

      

0


source







All Articles