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.
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:
And the result was like this:
Hope this helps.