setMaxDate为DatePickerDialog

时间:2016-04-21 11:46:40

标签: android datepicker

您好我实现了 DatePickerDialog ,但我想设置范围,我找到 setMinDate setMaxDate ,但我不知道如何投入价值观。我想为最小年龄为18岁且最大年龄为100岁的用户设置日历;我认为它的计算时间为毫秒。

    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);
DatePickerDialog dpd = new DatePickerDialog(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT, this, year, month, day);
dpd.getDatePicker().setMaxDate(max);
return dpd;

我不知道2016 - 18年我必须付出多大的价值。

2 个答案:

答案 0 :(得分:1)

我想这就是你需要的:

            final Calendar maxc = Calendar.getInstance();
            int year = maxc.get(Calendar.YEAR);
            maxc.set(Calendar.YEAR,year-18);
            datePickerDialog.getDatePicker().setMaxDate(maxc.getTimeInMillis());

            final Calendar minc = Calendar.getInstance();
            int year = minc.get(Calendar.YEAR);
            minc.set(Calendar.YEAR,year-100);
            datePickerDialog.getDatePicker().setMinDate(minc.getTimeInMillis());
            datePickerDialog.show();

答案 1 :(得分:1)

使用此代码,从当前日期设置最长日期和最短日期。

Calendar minCal = Calendar.getInstance();
minCal.set(Calendar.YEAR, minCal.get(Calendar.YEAR) - 100);
Calendar maxCal = Calendar.getInstance();
maxCal.set(Calendar.YEAR, maxCal.get(Calendar.YEAR) - 18);
dialog.getDatePicker().setMinDate(minCal.getTimeInMillis());
dialog.getDatePicker().setMaxDate(maxCal.getTimeInMillis());