how to restrict user to select date of birth who is under 21 years in android

浪尽此生 提交于 2019-12-10 11:56:01

问题


I am using DatePickerDialog to select the users date of birth.How to restrict user to select date of birth who is under 21 years from current date.

Eg:the users date of birth after 14/6/1996 should be restricted from selecting

This is my code,

 Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        c.add( Calendar.YEAR, -21 );
        minDate= c.getTime().getTime();
        Log.v(Constants.TAG, "selecteddsdf " + minDate);

   public void showDatePickerDialog(View v) {

    datePickerDialog = new DatePickerDialog(v.getContext(), new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {


            datePickerDialog.getDatePicker().setMinDate(minDate);

            Calendar newDate = Calendar.getInstance();
            newDate.set(year, monthOfYear, dayOfMonth);
            txtDOB.setText(dateFormatter.format(newDate.getTime()));
            uDOB = dateFormatter2.format(newDate.getTime());
            Log.e(Constants.TAG, "onDateSet: UserDob: " + uDOB);
        }

    }, year, month, date);

    datePickerDialog.show();
}

回答1:


You can use below method for that

datePickerDialog.getDatePicker().setMaxDate(minDate.getTime());

setup for minDate

 Date minDate = null;
 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
 try 
 {
         minDate = sdf.parse("31/12/1996");
 } 
 catch (ParseException e) 
 {
       e.printStackTrace();
  }



回答2:


try this

mDatePicker.getDatePicker().setMinDate(maxDate.getTimeInMillis());


来源:https://stackoverflow.com/questions/44545692/how-to-restrict-user-to-select-date-of-birth-who-is-under-21-years-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!