Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable future dates in Android Compose Material3 DatePicker?

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)
  }
}
like image 322
Chris Kobrzak Avatar asked Jan 25 '26 14:01

Chris Kobrzak


1 Answers

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.

Full example

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

Final product

enter image description here

Thanks to ianhanniballake for providing direction.

like image 122
Chris Kobrzak Avatar answered Jan 27 '26 04:01

Chris Kobrzak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!