-1

I want to open my DatePicker from current date to 18 years back for DateofBirth Validation.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • `LocalDate.now(yourTimeZone).minusYears(18)`. Using `LocalDate` from java.time, the modern Java date and time API, on Android requires either API level 26 or that you add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your project. When passing the month value from the `LocalDate` to your datepicker remember to subtract 1 because the date picker numbers months from 0. – Ole V.V. Oct 22 '19 at 08:00

2 Answers2

3

Just Add below line

 myCalendar.add(Calendar.YEAR,-18)
 new DatePickerDialog(getActivity(), dateExpiry, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
1

This might not be exactly what you have been looking for. But nevertheless you can have starting point and manipulate it. Please make sure to update the below mentioned answer.

Try this in the XML file:

<EditText
   android:id="@+id/Birthday"
   custom:font="@string/font_avenir_book"
   android:clickable="true"
   android:editable="false"
   android:hint="@string/birthday"/>

Now in Java File:

final Calendar myCalendar = Calendar.getInstance();

EditText edittext= (EditText) findViewById(R.id.Birthday);
DatePickerDialog.OnDateSetListener 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);
        updateLabel();
    }

};

edittext.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        new DatePickerDialog(classname.this, date, myCalendar
                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                myCalendar.get(Calendar.DAY_OF_MONTH)).show();
    }
});

Now add the method in the above activity.

private void updateLabel() {
    String myFormat = "MM/dd/yy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

    edittext.setText(sdf.format(myCalendar.getTime()));
}

Add android:focusable="false" within the xml file of the EditText to allow for a single touch.

This answer has been copied from Datepicker: How to popup datepicker when click on edittext.

cantona_7
  • 1,127
  • 4
  • 21
  • 40