How to set the limit on date in Date picker dialog

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 04:22:06
Kartheek

You have the setMinDate(long) and setMaxDate(long) methods at your disposal. Both of these will work on API level 11 and above. Since you are using a DatePickerDialog, you need to first get the underlying DatePicker by calling the getDatePicker() method.

dpdialog.getDatePicker().setMinDate(minDate);  
dpdialog.getDatePicker().setmaxDate(maxDate);  

Source :Set Limit on the DatePickerDialog in Android?

You can calculate the minDate by using,

Date today = new Date();
Calendar c = Calendar.getInstance();
c.setTime(today);
c.add( Calendar.MONTH, -6 ) // Subtract 6 months
long minDate = c.getTime().getTime() // Twice!  

Updated :

Replace the below line

return new DatePickerDialog(getActivity(), this, year, month, day);

with

 // Create a new instance of DatePickerDialog and return it
    DatePickerDialog pickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);
    pickerDialog.getDatePicker().setMaxDate(maxDate);
    pickerDialog.getDatePicker().setMinDate(minDate);
    return pickerDialog;

In some cases, when you set maximum date with a date without hours and minutes, you won't be able to select the maximum date you set. For instance

 Calendar maxDate = Calendar.getInstance();
            maxDate.set(Calendar.DAY_OF_MONTH, day + 5);
            maxDate.set(Calendar.MONTH, month);
            maxDate.set(Calendar.YEAR, year);

 datePickerDialog.getDatePicker().setMaxDate(maxDate.getTimeInMillis());

With the code block above, you can not click to your maxDate.

But if you add hours and minutes to like;

            maxDate.set(Calendar.HOUR, 23);
            maxDate.set(Calendar.MINUTE, 59);

to your maxDate, your last date will be clickable

by using

setMinDate and setMaxDate

MinDate

MaxDate

try this

DatePickerDialog dpDialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
DatePicker datePicker = dpDialog.getDatePicker();

Calendar calendar = Calendar.getInstance();//get the current day
datePicker.setMaxDate(calendar.getTimeInMillis());//set the current day as the max date or put yore date in miliseconds.
datePicker.setMinDate(calendar.getTimeInMillis());//set the current day as the min date or put your date in mili seconds format
return dpDialog;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!