Set Mindate And Maxdate In Datepicker
Creating app in which i am showing DatePicker.Now i want to set MinDate of DatePicker is previous two years and max date future two years only.Selection should be base on current d
Solution 1:
To set the min date two years before and max two years after today use the following code:
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -2); // subtract 2 years from now
datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
c.add(Calendar.YEAR, 4); // add 4 years to min date to have 2 years after now
datePickerDialog.getDatePicker().setMaxDate(c.getTimeInMillis());
Solution 2:
I believe this code really helps you to give the fix.
Here is the code for your fix -
privatevoidshowDateDailog() {
final DatePickerDialog datePickerDialog = new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
@Override
publicvoidonDateSet(DatePicker datePicker, int selectedYear, int selectedMonth, int selectedDate) {
year = selectedYear;
month = selectedMonth;
day = selectedDate;
((TextView) findViewById(R.id.textViewTORStartDate)).setText(new StringBuilder().append(day).append("/")
.append(month + 1).append("/").append(year));
}
}, year, month, day);
final Calendar calendar = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
//Min date setting part
cal.set(Calendar.MONTH, mm);
cal.set(Calendar.DAY_OF_MONTH, dd);
cal.set(Calendar.YEAR, yy - 2);
datePickerDialog.setMinDate(cal.getTimeInMillis());
//Maximum date setting part
Calendar calen = Calendar.getInstance();
calen.set(Calendar.MONTH, mm);
calen.set(Calendar.DAY_OF_MONTH, dd);
calen.set(Calendar.YEAR, yy + 2);
datePickerDialog.setMaxDate(calen.getTimeInMillis());
datePickerDialog.show();
}
Solution 3:
You can set MinDate and MaxDate for that you will need to use DatePicker
class.
classMDatePickerDialogextendsDatePickerDialog {
MDatePickerDialog(Context c) {
super(c, null, 2016, 11, 23);
Datemin=newDate(2018-1900, 4, 21);
DatePickerp= getDatePicker();
CalendarViewcv= p.getCalendarView();
longcur= cv.getDate();
intd= cv.getFirstDayOfWeek();
p.setMinDate(min.getTime());
cv.setDate(cur + 1000L*60*60*24*40);
cv.setFirstDayOfWeek((d + 1) % 7);
cv.setDate(cur);
cv.setFirstDayOfWeek(d);
}
}
Hope this will help you.
Solution 4:
You can get the underlying DatePicker from a DatePickerDialog (by simply calling getDatePicker()) and set its bounds using:
setMinDate(long minDate)
setMaxDate(long maxDate)
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 pass current date and add or substract x years from that..
Post a Comment for "Set Mindate And Maxdate In Datepicker"