Reputation: 342
I have created a DatePickerDialog and I am trying to limit the picker to the max date of "today" (currently: 2020, 13 Jul), like this:
DatePickerDialog(
activity,
OnDateSetListener { _: DatePicker?, year: Int, monthOfYear: Int, dayOfMonth: Int ->
selectedBirthday.set(year, monthOfYear, dayOfMonth)
},
1980, 7, 2
).apply {
datePicker.maxDate = System.currentTimeMillis() // max date = today
}.show()
The dialog opens correctly with default data ("1980, Aug 02").
However, I have found a bug when "1980, Aug 02" is selected and I change the year to 2020: The dialog then shows "2020, Aug 02" on top ignoring the maxDate limit setup on the datePicker, but the calendar below is correctly limited to July 13.
If I click on "OK" button, the year, monthOfYear and dayOfMonth returned on my DateSetListener are 2020, Aug, 02, which is a future date from what I wanted. Is there any workaround to avoid this bug on the DatePickerDialog with the maxDate being ignored?
Upvotes: 2
Views: 636
Reputation: 1642
It is a known bug. There is a ticket recorded 2020-09-29 and still open (in assigned state) as of 2022-02-08.
A similar bug tracker entry with the same issue created 2019-02-19 was closed on 2019-12-04 as "won't fix" due to it being low priority.
I am sorry to say this, but I believe this is not going to be fixed.
However, what you can do is extend the android.app.DatePickerDialog
to introduce a fix yourself:
class MyDatePickerDialog(context: Context) : DatePickerDialog(context) {
override fun onDateChanged(view: DatePicker, year: Int, month: Int, dayOfMonth: Int) {
val newDate = Calendar.getInstance().apply { set(year, month, dayOfMonth) }
val minDate = Date(datePicker.minDate)
val maxDate = Date(datePicker.maxDate)
newDate.time = minOf(maxDate, maxOf(minDate, newDate.time))
super.onDateChanged(
view,
newDate.get(Calendar.YEAR),
newDate.get(Calendar.MONTH),
newDate.get(Calendar.DAY_OF_MONTH)
)
}
}
Upvotes: 1
Reputation: 4039
Please try Date().getTime()
instead of System.currentTimeMillis()
DatePickerDialog(
activity,
OnDateSetListener { _: DatePicker?, year: Int, monthOfYear: Int, dayOfMonth: Int ->
selectedBirthday.set(year, monthOfYear, dayOfMonth)
},
1980, 7, 2
).apply {
datePicker.maxDate = Date().getTime() // max date = today
}.show()
Upvotes: 0