Android Datepicker Min Max Date Before API Level 11

How set maximum date in datepicker dialog in android?

Use setMaxDate().

For example, replace return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay) statement with something like this:

    DatePickerDialog dialog = new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
dialog.getDatePicker().setMaxDate(new Date().getTime());
return dialog;

How to set the limit on date in Date picker dialog

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;

Set MinDate and MaxDate in DatePIcker

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());

Set maximum Date in DatePicker

100 * 12 * 30 * 24 * 60* 60 * 1000

This expression is computed with 32-bit int precision but the value is much too large to fit in 32 bits. To compute with 64-bit long, make one of the factors a long with L, e.g.

100L * 12 * 30 * 24 * 60* 60 * 1000

However, consider using Calendar for datetime math like this. For example,

Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -100);
long hundredYearsAgo = c.getTimeInMillis();

and then set hundredYearsAgo as the minDate and current time as maxDate.



Related Topics



Leave a reply



Submit