android datepicker 18 year old validation

android, datepicker

Solution

try using the Calendar class.

public void onDateSet(DatePicker view, int year, int month, int day) {
    Calendar userAge = new GregorianCalendar(year,month,day);
    Calendar minAdultAge = new GregorianCalendar();
    minAdultAge.add(Calendar.YEAR, -18);
    if (minAdultAge.before(userAge)) {
        SHOW_ERROR_MESSAGE;
    } 
}

this should do what you want :)

Problem

I am using this code to set custom date for datepicker .. // method to create date picker dialog ``` public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // set default date final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { // get selected date mYear = year; mMonth = month; mDay = day; // show selected date to date button dob.setText(new StringBuilder() .append(mYear).append("-") .append(mMonth + 1).append("-") .append(mDay).append(" ")); } } ``` My scenario is that when ever user set a date the date should verify that user is atleast 18 year old ..otherwise it will show alert user is atleast 18 year old ..

Original source