在 DatePicker 中验证 18 岁

Validation 18 years old in DatePicker

我正在尝试设置一个日期选择器,用户可以在其中选择日期,如果未满 18 岁,则显示一条消息。

到目前为止,我知道日期选择器无法选择未来的日期,但我不知道如果用户的日期未满 18 岁,如何设置条件来检查。任何帮助将不胜感激。

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

如果你想将 18 年前的纪元毫秒设置为你的选择器的 max/starting 日期,你可以使用:

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

或者如果你想验证,你可以这样比较:

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