Search code examples
androidkotlindatepickerandroid-edittext

Validation 18 years old in DatePicker


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

Solution

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