Home > Enterprise >  Android(Kotlin) Material Design Date Range Picker How to set Minimum and Maximum dates properly?
Android(Kotlin) Material Design Date Range Picker How to set Minimum and Maximum dates properly?

Time:10-18

I have a Date Range Picker(Material Design) and I want to disable previous dates(so minimum date will be current day), and maximum date will be 6 months later. I tried something like this:

    val calendar = Calendar.getInstance()
    val constraintsBuilderRange = CalendarConstraints.Builder()
    val dateValidatorMin: CalendarConstraints.DateValidator = DateValidatorPointForward.from(calendar.timeInMillis)
    val dateValidatorMax: CalendarConstraints.DateValidator = DateValidatorPointBackward.before(calendar.timeInMillis 100000000)

    val listValidators = ArrayList<CalendarConstraints.DateValidator>()
    listValidators.add(dateValidatorMin)
    listValidators.add(dateValidatorMax)
    val validators = CompositeDateValidator.allOf(listValidators)
    constraintsBuilderRange.setValidator(validators)


    val datePicker = MaterialDatePicker.Builder.dateRangePicker()
        .setTitleText("Select range")
        .setCalendarConstraints(constraintsBuilderRange.build())
        .build()

    datePicker.show(
        this.requireFragmentManager(),"date_range_picker"
    )

This worked but I randomly give 100000000 to dateValidatorMax. So how can I achieve 6 months later in milliseconds? And how can I get 1 day before currentDate in dateValidatorMin?

CodePudding user response:

So I solved this problem thanks to Kotlin, there is a really easy method:

val dateValidatorMin: CalendarConstraints.DateValidator = DateValidatorPointForward.from(calendar.timeInMillis - 1.days.toLong(
        DurationUnit.MILLISECONDS))
val dateValidatorMax: CalendarConstraints.DateValidator = DateValidatorPointBackward.before(calendar.timeInMillis  180.days.toLong(
        DurationUnit.MILLISECONDS))
  • Related