问题
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