0

I'm trying to set a datepicker where the user will choose a date and if it's under 18 years old and if not it will show a message.

Until now I have that the date picker can't choose future dates, but I don't know how to make the condition to ckeck if the user's date has under 18 years. Any help would be appreciated.

fun setupBirthdateDatePicker() {
    val c: Calendar = Calendar.getInstance()
    val year: Int = c.get(Calendar.YEAR)
    val month: Int = c.get(Calendar.MONTH)
    val day: Int = c.get(Calendar.DAY_OF_MONTH)

    setClickListener {
        val dialog = if (textInput.text.isNullOrEmpty()) {
            DatePickerDialog(context,
                { view, year, month, dayOfMonth ->
                    textInput.setText(Utils.getDateFromDatePicker(year, month, dayOfMonth))
                }, year, month, day)
        } else {
            DatePickerDialog(context,
                { view, year, month, dayOfMonth ->
                    textInput.setText(Utils.getDateFromDatePicker(year, month, dayOfMonth))
                },
                Utils.getYearFromDate(textInput.text.toString()),
                Utils.getMonthFromDate(textInput.text.toString()),
                Utils.getDayFromDate(textInput.text.toString()))
        }
       
        dialog.datePicker.maxDate = c.timeInMillis
        dialog.show()
    }
}
Mario Muresean
  • 233
  • 1
  • 5
  • 16
  • You could use a solution [that calculates age in years](https://stackoverflow.com/a/59609344/1712135) and check if the result is `≥ 18`. You can instantiate a `LocalDate` by `LocalDate.of(year, month, dayOfMonth)` in your case. Please stop using `Calendar` and other totally outdated classes, use `java.time` instead. – deHaar Nov 09 '21 at 15:55

1 Answers1

2

If you want 18 years ago in epoch milliseconds to set as the max/starting date of your picker, you can use:

(ZonedDateTime.now() - Period.ofYears(18)).toInstant().toEpochMilli()

Or if you want to validate, you can compare like this:

val eighteenYearsAgo = LocalDate.now() - Period.ofYears(18)

val listener = DatePickerDialog.OnDateSetListener { _, year, month, day ->
    // +1 month because DatePicker's month is unfortunately zero-based
    val pickedDate = LocalDate.of(year, month + 1, day) 
    if (pickedDate < eighteenYearsAgo) {
        // Picked a date less than 18 years ago
    }
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154