1
votes

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.

Screenshot: Android DatePickerDialog ignores maxDate

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?

1
Please try my answer. Let me know if it's not worked? - Shalu T D
I haven't been able to reproduce the issue. One thing you can try is to update selected date right below the line where you set the maximum date inside of apply block: updateDate(1980, 7, 2). - Jenea Vranceanu
@JeneaVranceanu Feel free to copy and paste the code to reproduce it! The steps when the dialog appears are: 1. Select a past year (for example: 1980) 2. Select a "future" month&day (for example: 02, Sept) 3. Select the current year (2020) - user3429953
@ShaluTD Sorry, it didn't... - user3429953

1 Answers

1
votes

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