How to restrict the user of DatePicker, you can choose only the date until today - 18 years

How to limit the use of DatePicker, you will not be able to select a date in the future. I have a DatePicker in action that is used to register. What to do, the user cannot select the date of birth if the user is less than 18 years old (for example, it is impossible to select a date after today - 18 years)?

+6
source share
3 answers

You did not indicate what level of API. In Honeycomb and then DatePicker has setMin / MaxDate methods that you can use to limit the valid range.

+2
source

I hope you have received an answer so far. The following may be useful for others: If you want to disconnect a user to select a date 18 years after today, here is what you can do.

Get time from 1-JAN-1970 to 18 years (in milliseconds)

Calendar cal = Calendar.getInstance(); cal.set(cal.get(Calendar.YEAR)+18,cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), 0); long time = cal.getTimeInMillis(); 

set it as the maximum allowed date in datepicker

  datepicker2.setMaxDate(time); 

Hope this helps anyone looking for an answer.

+2
source

Count the year to 18 from the current (current year) using int minYear = currentYear - 18; And then set this date with (Min. Year, current month, current day) as the maximum date selection limit.

  private static void setMaxLimitInDatePicker(DatePickerDialog datePickerDialog) { final Calendar calendar = Calendar.getInstance(); int currentYear = calendar.get(Calendar.YEAR); int currentMonth = calendar.get(Calendar.MONTH); int currentDay = calendar.get(Calendar.DAY_OF_MONTH); int minYear = currentYear - 18; int minMonth = currentMonth; int minDay = currentDay; calendar.set(minYear, minMonth, minDay); long minDateInMilliSeconds = calendar.getTimeInMillis(); // Set 18 years from today as max limit of date picker datePickerDialog.getDatePicker().setMaxDate(minDateInMilliSeconds); } 
0
source

Source: https://habr.com/ru/post/907838/


All Articles