Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android datepicker 18 year old validation

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 ..

like image 571
Khawaja Absar Avatar asked Jan 27 '14 18:01

Khawaja Absar


2 Answers

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 :)

like image 111
dy_ Avatar answered Oct 26 '22 18:10

dy_


Try this

datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() - 568025136000L);
like image 27
Ketan Ramani Avatar answered Oct 26 '22 19:10

Ketan Ramani