1

I am trying to create a DatePicker in android for selecting Date of birth of a user. i want to set the year in a way that the age selected from the datepicker is greater than 18 years. For eg. if someone clicks on datetimepicker dialog, he/she should see max year as 1998 as its is equivalent to 18 years.

My code goes like:

            dobDatePicker = new DatePickerDialog(getContext(), AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                candidateDob.setText(dateFormatter.format(newDate.getTime()));
            }
        },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
        dobDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());

so for now, the restriction is till the current date. Please help :)

Adarsh Raj
  • 183
  • 1
  • 3
  • 12

2 Answers2

3

See these two lines:

newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
dobDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());

You are setting the maxDate as the current year. Try something like this:

Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -18);
dobDatePicker.getDatePicker().setMaxDate(c.getTime());
Todor Kostov
  • 1,789
  • 1
  • 13
  • 20
2

dobDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis() - (long) 1000 * 60 * 60 * 24 * 365 * 18); But it doesn't take into account leap years, so there's probably some other trick with Calendar

Wukash
  • 666
  • 5
  • 9