MaterialDatePicker constraints or limit available dates

882 Views Asked by At

I have a requirements where I need to limit the allowed date in DatePicker from year 2009 up to current date only. Meaning the supported date for example will be from Jan 1, 2009 up to current date only.

The current implementation we had with the old DatePickerDialog

val calendar = Calendar.getInstance()
        val year = calendar[Calendar.YEAR]
        val month = calendar[Calendar.MONTH]
        val day = calendar[Calendar.DAY_OF_MONTH]

        val datePickerDialog = DatePickerDialog(appContext,
            R.style.AppDatePicker,
            dateSetListener,
            year,
            month,
            day)

        //Oldest date will be 2009
        calendar.add(Calendar.YEAR, 2009 - year)
        datePickerDialog.datePicker.minDate = calendar.timeInMillis

        //Latest date will be the current date
        datePickerDialog.datePicker.maxDate = System.currentTimeMillis()
//        datePickerDialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        //Pop up the DatePicker dialog
        datePickerDialog.show()

Additional possible improvement is to limit the supported date by specifying the date statically. Something like

val startDate = "01/01/2009"
val endDate = "03/27/2022"

calendarPicker.minDate = Date(startDate)
calendarPicker.maxDate = Date(endDate)

Currently looking on CalendarConstraints.DateValidator and CalendarConstraints.Builder() but do not know how to work with it base on my requirements.

1

There are 1 best solutions below

0
On

I don't know if you still need it, but maybe it will help others too.

I had a similar problem where I needed only dates in the range from the previous day to 45 days behind the current date to be enabled. That is, today, January 18th, the calendar would only be enabled from 12-05-2022 to 01-17-2023.

I did it like this:

val dateValidatorMin: DateValidator =
    DateValidatorPointForward.from(
        Calendar.getInstance().timeInMillis - 45.days.toLong(DurationUnit.MILLISECONDS))

val dateValidatorMax: DateValidator =
    DateValidatorPointBackward.before(
        Calendar.getInstance().timeInMillis - 1.days.toLong(DurationUnit.MILLISECONDS))
    enter code here

val dateValidator: DateValidator = CompositeDateValidator.allOf(listOf(dateValidatorMin, dateValidatorMax))

val constraints: CalendarConstraints =
    CalendarConstraints.Builder()
        .setValidator(dateValidator)
        .build()

val builder = MaterialDatePicker.Builder.dateRangePicker()
    .setCalendarConstraints(constraints)
    .setTitleText(getString(R.string.label_select_date_range))

val picker = builder.build() 

And the result was like this:

image showing the range of days enabled

Hope this helps.