android datepicker 18岁验证

时间:2014-01-27 18:00:30

标签: android datepicker

我正在使用此代码为datepicker设置自定义日期。 //创建日期选择器对话框的方法

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(" "));
    }
}

我的情况是,当用户设置日期时,日期应该验证用户是否至少18岁..否则它将显示提醒用户至少18岁..

2 个答案:

答案 0 :(得分:20)

尝试使用Calendar类。

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;
    } 
}

这应该做你想要的:)

答案 1 :(得分:0)

尝试一下

datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() - 568025136000L);