I have a DatePickerDialog with a DatePicker, both imported from the androidx.compose.material3 package. I believe it should be possible to disable future dates with the dateValidator DatePicker property but I would appreciate some help with the implementation.
A simplified version of my code looks like this:
@Composable
@OptIn(ExperimentalMaterial3Api::class)
fun PastOrPresentDatePicker() {
val state = rememberDatePickerState()
DatePickerDialog(
onDismissRequest = { ... },
confirmButton = { ... },
dismissButton = { ... }
) {
DatePicker(state)
}
}
Answering my own question just in case someone else finds it useful.
TL;DR
The rememberDatePickerState helper that you would typically use with the DatePicker composable accepts selectableDates that can be used to allow or disallow certain dates.
Make sure you have and alpha or beta version of material3 listed as a dependency in build.gradle.kts:
dependencies {
implementation("androidx.compose.material3:material3:1.2.0-beta01")
}
Consider creating the following helper for reuse:
// PastOrPresentSelectableDates.kt
object PastOrPresentSelectableDates: SelectableDates {
override fun isSelectableDate(utcTimeMillis: Long): Boolean {
return utcTimeMillis <= System.currentTimeMillis()
}
override fun isSelectableYear(year: Int): Boolean {
return year <= LocalDate.now().year
}
}
Use it in your composable view:
// PastOrPresentDatePicker.kt
@Composable
fun PastOrPresentDatePicker() {
val state = rememberDatePickerState(
selectableDates = PastOrPresentSelectableDates
)
DatePickerDialog(/* your params here */) {
DatePicker(state)
}
}

Thanks to ianhanniballake for providing direction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With