Question

How to limit on DatePickerDialog to choose a date from 2-12 years in the past or from 0-2 years from the current date?

I have DatePickerDialog in activity which is used for getting the date of birth for child and infant. Child age will be (2-12yrs) and infant age can be (0-2ys). If I pass 1 then the age limit should be (2-12yrs) and if I pass 2 the age limit should be (0-2yrs).

What could I do to get this functionality in my calendar?

My Calender code is:

date = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                // TODO Auto-generated method stub
                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH, monthOfYear);
                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                String myFormat = "dd/MM/yy"; //In which you need put here
                SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                dateofBirth.setText(sdf.format(myCalendar.getTime()));
            }
        };

dateofBirth.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDialog(DATE_DIALOG_ID);

            }
        });

public Dialog onCreateDialog(int id) {
    final Calendar now = Calendar.getInstance();

    switch (id) {
    case DATE_DIALOG_ID:
        // set date picker as current date
        DatePickerDialog _date =   new DatePickerDialog(this, date,myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH)){
            @Override

            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth){   

                if (year > now.get(Calendar.YEAR))

                    view.updateDate(myCalendar
                            .get(Calendar.YEAR), myCalendar
                            .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));

                if (monthOfYear > now.get(Calendar.MONTH) && year == now.get(Calendar.YEAR))
                    view.updateDate(myCalendar
                            .get(Calendar.YEAR), myCalendar
                            .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));

                if (dayOfMonth > now.get(Calendar.DAY_OF_MONTH) && year == now.get(Calendar.YEAR) && 
                        monthOfYear == now.get(Calendar.MONTH))
                    view.updateDate(myCalendar
                            .get(Calendar.YEAR), myCalendar
                            .get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
            }

        };

        return _date;
    }
    return null;
}
Was it helpful?

Solution

All the other answers seem rather convoluted, so I'm just going to state the obvious: you can get the underlying DatePicker from a DatePickerDialog (by simply calling getDatePicker()) and set its bounds using:

Where the argument is the usual number of milliseconds since January 1, 1970 00:00:00 in the default time zone. You'll still have to calculate these values of course, but that should be trivial to do with the Calendar class: just take the current date and add or substract x years.

The more attentive reader will notice that the aforementioned setters weren't available until API level 11. If you're targeting that (or newer) platform only, then you're good to go. If you also want to support i.e. Gingerbread devices (Android 2.3 / API level 9+), you can use a backported version of DatePicker in stead.

OTHER TIPS

Setting minumum and maximum date for the DatePickerDialog is not enough. User can click on the year and scroll in between years.

You should also set year range on the DatePicker like this:

datePicker.setYearRange(calendar.get(Calendar.YEAR), calendar.get(Calendar.YEAR) + 1);

I am not in a position to give you the working code, since I am on a tour and didn't have access to my PC. but I can give you a way to achieve your aim (or so i think).

I am not sure this will work perfectly, but any way worth a try.

Pls try this code and inform me.

"DatepickerType" is an Integer public Member variable of the class.

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

    // when dialog box is closed, below method will be called.
    public void onDateSet(DatePicker view, int selectedYear,
            int selectedMonth, int selectedDay) {
        int y = Calendar.getInstance().get(Calendar.YEAR);
        switch(DatepickerType){
        case 1:
            if(selectedYear>(y-2)){
                //Add message if you want
                selectedYear = y-2;
            }
                else if(selectedYear<(y-12)) {
                //Add msg if u want
                    selectedYear = y-12;
            }

        case 2:
            if(selectedYear>(y)){
                //Add message if you want
                selectedYear = y;
            }
                else if(selectedYear<(y-2)) {
                //Add msg if u want
                    selectedYear = y-2;
            }
        }

        String year1 = String.valueOf(selectedYear);
        String month1 = String.valueOf(selectedMonth+1);
        String day1 = String.valueOf(selectedDay);
        //do what you need
        setLastStatus();

    }
};
    datePickerDialog = new CustomDatePickerDialog(this,
                new OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                            int monthOfYear, int dayOfMonth) {
                        // TODO Auto-generated method stub
                        try {
                            Log.i("DAta SEt", "data set");
                        } catch (Exception e) {

                        }

                    }

                }, minYear, minMonth, minDay, maxYear, maxMonth, maxDay);

CustomDatePickerDialog:

public class CustomDatePickerDialog extends DatePickerDialog {

private boolean mIgnoreEvent = false, mignorsunday = true;

public static int mYear, mMonth, mDate, maxYear, maxMonth, maxDay, minYear,
        minMonth, minDay;
public static int dateflag = 0;
public static int dateflag2 = 0;

public CustomDatePickerDialog(Context context, OnDateSetListener callBack,
        int year, int monthOfYear, int dayOfMonth, int maxYear,
        int maxMonth, int maxDay) {
    super(context, callBack, year, monthOfYear, dayOfMonth);
    // TODO Auto-generated constructor stub
    dateflag = 0;
    dateflag2 = 1;
    mYear = year;
    mMonth = monthOfYear;
    mDate = dayOfMonth;

    Log.i("Hello World ::", "Please Its Updating At Every time");

    this.maxYear = maxYear;
    this.maxMonth = maxMonth;
    this.maxDay = maxDay;
    this.minYear = year;
    this.minMonth = monthOfYear;
    this.minDay = dayOfMonth;

    // setTitle("בחרו מתי נח לכם שנתקשר");
    setTitle("We Call U...בחרו מתי נוח לכם ש");

}

@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
    // TODO Auto-generated method stub
    super.onDateChanged(view, year, month, day);
    dateflag = 1;
    dateflag2 = 1;
    if (!mIgnoreEvent) {
        mIgnoreEvent = true;
        if (year > maxYear || month > maxMonth && year == maxYear
                || day > maxDay && year == maxYear && month == maxMonth) {
            mYear = maxYear;
            mMonth = maxMonth;
            mDate = maxDay;
            view.updateDate(maxYear, maxMonth, maxDay);
        } else if (year < minYear || month < minMonth && year == minYear
                || day < minDay && year == minYear && month == minMonth) {
            mYear = minYear;
            mMonth = minMonth;
            mDate = minDay;
            view.updateDate(minYear, minMonth, minDay);
        } else {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, month);
            cal.set(Calendar.DATE, day);
            if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {

                if (mignorsunday) {
                    cal.add(Calendar.DATE, 1);
                    mYear = cal.get(Calendar.YEAR);
                    mMonth = cal.get(Calendar.MONTH);
                    mDate = cal.get(Calendar.DATE);
                    mignorsunday = false;
                } else if (!mignorsunday) {
                    mignorsunday = true;
                    cal.add(Calendar.DATE, -1);
                    mYear = cal.get(Calendar.YEAR);
                    mMonth = cal.get(Calendar.MONTH);
                    mDate = cal.get(Calendar.DATE);
                }
            } else {
                mYear = year;
                mMonth = month;
                mDate = day;
            }
            view.updateDate(mYear, mMonth, mDate);
        }
        setTitle("We Call U...בחרו מתי נוח לכם ש");
        mIgnoreEvent = false;
    }
}

public int getSelectedYear() {
    return mYear;
}

public int getSelectedMonth() {
    return mMonth;
}

public int getSelectedDate() {
    return mDate;
}
}

Here is the working code, you have to do some changes according to your code. Like you can add min and max age for child and infant.

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

    public void onDateSet(DatePicker view, int year, int monthOfYear,
                          int dayOfMonth) {
    /*
     * mYear = year;
     * mMonth = monthOfYear;
     * mDay = dayOfMonth;
     */
        if (year > maxYear || monthOfYear > maxMonth && year == maxYear ||
                dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth) {
            view.updateDate(maxYear, maxMonth, maxDay);
            //you can add toast message here for max year selection
        } else if (year < minYear || monthOfYear < minMonth && year == minYear ||
                dayOfMonth < minDay && year == minYear && monthOfYear == minMonth) {
            view.updateDate(minYear, minMonth, minDay);
            //you can add toast message here for min year selection
        } else {
            view.updateDate(year, monthOfYear, dayOfMonth);
        }
    }

};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mPickDate = (Button) findViewById(R.id.pickDate);
    mPickDate.setOnClickListener(this);

    final Calendar c = Calendar.getInstance();
    mYear = c.get(Calendar.YEAR);
    mMonth = c.get(Calendar.MONTH);
    mDay = c.get(Calendar.DAY_OF_MONTH);

    maxYear = mYear - 2;//make a proper condition to change it the based on the   child/infant
    maxMonth = mMonth;
    maxDay = mDay;

    minYear = mYear - 12;//make a proper condition to change it the based on the child/infant
    minMonth = mMonth;
    minDay = mDay;

}

@Override
public void onClick(View v) {
    showDialog(DATE_DIALOG_ID);
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this, mDateSetListener, mYear - minYear,
                    mMonth, mDay);
    }
    return null;
}

May this help you. Better to use dialog fragment since showDialog() of Dialog is deprecated. Also keep in mind it will work only in API Higher than 11. So, change min.sdk in the manifest to 11.

Calendar calendar=Calendar.getInstance();
    int mDay = calendar.get(Calendar.DAY_OF_MONTH), mMonth = calendar.get(Calendar.MONTH), mYear = calendar.get(Calendar.YEAR);


    int minDay = calendar.get(Calendar.DAY_OF_MONTH), minMonth = calendar.get(Calendar.MONTH), minYear = calendar.get(Calendar.YEAR)-12;

int maxDay = calendar.get(Calendar.DAY_OF_MONTH), maxMonth = calendar.get(Calendar.MONTH), maxYear = calendar.get(Calendar.YEAR)-12;


public void onDate(View view) {
        System.out.println("hello");
        DialogFragment fragment = new SelectDateFragment();
        fragment.show(getFragmentManager(), "Date Picker");
    }

    class SelectDateFragment extends DialogFragment implements
            DatePickerDialog.OnDateSetListener {

        public Dialog onCreateDialog(Bundle savedInstanceState) {


            System.out.println("entrering on create dialog");;

            return new DatePickerDialog(getActivity(), this, mYear, mMonth,
                    mDay) {

                public void onDateChanged(DatePicker view, int year,
                        int monthOfYear, int dayOfMonth) {
                    System.out.println("----------onDateChanged()-----------"
                            + year + "--" + year);
                    System.out.println("----------onDateChanged()-----------"
                            + monthOfYear + "--" + monthOfYear);
                    System.out.println("----------onDateChanged()-----------"
                            + dayOfMonth + "--" + dayOfMonth);

                    if ((minYear < year)
                            || ((minMonth < monthOfYear) && (minYear == year))
                            || ((minDay < dayOfMonth) && (minYear == year) && (minMonth == monthOfYear))) {
                        view.updateDate(minYear, minMonth - 1, minDay);

                    }

if ((maxYear > year)
                            || ((maxMonth > monthOfYear) && (maxYear == year))
                            || ((maxDay > dayOfMonth) && (maxYear == year) && (maxMonth == monthOfYear))) {
                        view.updateDate(maxYear, maxMonth - 1, maxDay);

                    }

                }
            };

        }

        @Override
        public void onDateSet(android.widget.DatePicker view, int year,
                int monthOfYear, int dayOfMonth) {
            System.out.println("year=" + year + "day=" + dayOfMonth + "month="
                    + monthOfYear);
            mYear=year;
            mMonth=monthOfYear;
            mDay=dayOfMonth;

            onPopulateSet(year, monthOfYear + 1, dayOfMonth);

        }


        private void onPopulateSet(int year, int i, int dayOfMonth) {
            EditText et_setDate;
            et_setDate = (EditText) findViewById(R.id.register_et_dob);
            et_setDate.setText(dayOfMonth + "/" + i + "/" + year);
            System.out.println("enetring on populate Set");

        }

    }
val cal = Calendar.getInstance()
            todayDay = cal.get(Calendar.DAY_OF_MONTH)
            todayMonth = cal.get(Calendar.MONTH)
            todayYear = cal.get(Calendar.YEAR)
            todayHour = cal.get(Calendar.HOUR)
            todayMin = cal.get(Calendar.MINUTE)


            val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { it, selectedYear, selectedMonth, selectedDay ->
                dateDisplay.isVisible = true
                val selectedDate = "$selectedDay/${selectedMonth + 1}/$selectedYear"
                //Implementing SimpleDateFormat
                val sdf = SimpleDateFormat("dd/mm/yyyy", Locale.ENGLISH)
                val formatedDate = sdf.parse(selectedDate)
                //this variable is of type Date
                val selectedTime = formatedDate!!.time / 60000


                val todayDate = sdf.parse(sdf.format(System.currentTimeMillis()))
                val todayTime = todayDate!!.time / 60000

                dateDisplay.text = formatedDate.toString()
                ageInMins.text = (todayTime - selectedTime).toString()

            }, todayYear, todayMonth, todayDay)
            dpd.datePicker.setMaxDate(Date().time - 86400000)
            dpd.datePicker.setBackgroundColor(Color.RED)
            dpd.show()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top