Search code examples
androidcalendardatepickerdialog

Set minimum year (use to select DOB) for Datepicker dialog


I have create a function for my code which set a rule to restrict user to select the day earlier then systems date from date picker dialog

protected void setMinMax() {
    Calendar minAllowedDate = CommUtils.getMinAllowedDate();
    minAllowedDate.add(Calendar.MILLISECOND, -1000);
      datePickerDialog.getDatePicker().setMinDate(minAllowedDate.getTimeInMillis());

now i want to create another date picker for user to select DOB, what i want to do is to set a rules that user DOB should be on age 4-150 which means the YEAR that user can select should be -4 & -150 from systems date. If using the the code above, what should i put in

minAllowedDate.add(Calendar.MILLISECOND, -1000);

i had tried with below code which give me the year 150 as min option

minAllowedDate.add(Calendar.YEAR, -150);

Solution

  • Found out that most of the solution using the method .add(Calendar.YEAR,-4), however this also create limit to the month & date to be select. For example, When the current date is 11/Jun/2018, running that line of code you can have 4 years before(2018-4=2014) but also limit in your month + day which you can only select date before 11/Jun/2018.

    After several tried, i had came out the solution which manually set the day & month to 31/Dec so that i can have an option range from 31/12/2014 to 1/1/2014

        Calendar calStart = new GregorianCalendar();
        calStart.setTime(new Date());
        calStart.set(Calendar.MONTH, 11);
        calStart.set(Calendar.DAY_OF_MONTH, 31);
        calStart.add(Calendar.YEAR, -150);
    
        Calendar calEnd = new GregorianCalendar();
        calEnd.setTime(new Date());
        calEnd.set(Calendar.MONTH, 11);
        calEnd.set(Calendar.DAY_OF_MONTH, 31);
        calEnd.add(Calendar.YEAR,-4);
        datePickerDialog.getDatePicker().setMinDate(calStart.getTimeInMillis());
        datePickerDialog.getDatePicker().setMaxDate(calEnd.getTimeInMillis());