Reputation: 1769
Android DatePicker
dialog
to select next 10 year date
only.
I have datepicker dialog in which I want to select only future date
(next 10 year) and prevent to select past date.
Below is my code which avoid to select past date but I want to show only next 10 year date too.
try {
dateFormatter = new SimpleDateFormat("MM/yy", Locale.US);
edtMonth.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year+2, monthOfYear, dayOfMonth);
edtMonth.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
// it is used for prevent old date selection.
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()+2);
} catch (Exception e) {
e.printStackTrace();
}
Thanks in advance.
Upvotes: 2
Views: 755
Reputation: 1388
try this
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.YEAR, 10);
Date newDate = cal.getTime();
datePicker.getDatePicker().setMinDate(System.currentTimeMillis());
datePicker.getDatePicker().setMaxDate(newDate.getTime());
Upvotes: 1
Reputation: 20930
To Display only 10 year from Today you have to set your MinDate
to System.currentTimeMillis()
and set MaxDate
to CureentTimeMillis + Next 10 Year Millis
and add this value to your MaxDate
like below way.
To setMinDate
Today.
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
To setMaxDate
Today.
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() + 10 year Millis);
Upvotes: 3