Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last day of DatePickerDialog is not selectable after setting max date

Tags:

android

After using setMaxDate to limit the number of days selectable on the DatePickerDialog, the last day is not greyed out but is not selectable. Thank you for your help in advance.

private void showDatePickerDialog() {
    DateTime dateTime = new DateTime();
    DateTime tomorrow = dateTime.plusDays(1);
    int year = tomorrow.getYear();
    int month = tomorrow.getMonthOfYear() -1; // zero based months
    int day = tomorrow.getDayOfMonth();

    DateTime thirtyDaysInFuture = dateTime.plusDays(30);

    long tomorrowMilliseconds = tomorrow.getMillis();
    long futureMilliseconds = thirtyDaysInFuture.getMillis();


    Log.d(TAG, "YEAR: " + year + ", MONTH: " + month + ", DAY: " + day);

    DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
            Log.d(TAG, i + ", " + i1 + ", " + i2);

        }
    }, year, month, day);

    datePickerDialog.getDatePicker().setMinDate(tomorrowMilliseconds);
    datePickerDialog.getDatePicker().setMaxDate(futureMilliseconds);
    datePickerDialog.show();
}
like image 594
Aaron E. Avatar asked Oct 13 '15 14:10

Aaron E.


2 Answers

I had a similar problem and I solved it by setting the hour, minute and second of the max date to 23, 59 and 59 respectively.

DatePickerDialog datePickerDialog = new DatePickerDialog(this, 
        new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // Add your code here
            }
        }, year, month, day);

Calendar maxDate = Calendar.getInstance();
maxDate.set(Calendar.HOUR_OF_DAY, 23);
maxDate.set(Calendar.MINUTE, 59);
maxDate.set(Calendar.SECOND, 59);
datePickerDialog.getDatePicker().setMaxDate(maxDate.getTimeInMillis());
like image 115
iRuth Avatar answered Nov 16 '22 10:11

iRuth


I had same problem and I found an answer. Try to use this code:

First you should reset current date, it's hours, minutes and seconds

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        calendar.add(Calendar.DAY_OF_YEAR, 14); //I set max date +2 weeks
        calendar.add(Calendar.HOUR_OF_DAY, 23);
        calendar.add(Calendar.MINUTE, 59);
        calendar.add(Calendar.SECOND, 59);

        dlgDate.getDatePicker().setMaxDate(calendar.getTimeInMillis());

Hope I help you

like image 34
vlasentiy Avatar answered Nov 16 '22 10:11

vlasentiy