Android Date Picker Dialog With Java Time (Kotlin)

July 24, 2018

JavaDatePickerDialog

class JavaDatePickerDialog : DialogFragment() {
    private var onDateSetListener: DatePickerDialog.OnDateSetListener? = null

    lateinit var localDate: LocalDate
    var onOk: ((date: LocalDate) -> Unit)? = null
    var onCancel: (() -> Unit)? = null

    companion object {
        private const val TAG = "JavaDatePickerDialog"

        private const val EXTRA_DATE = "date"

        fun newInstance(date: LocalDate? = null): JavaDatePickerDialog {
            val dialog = JavaDatePickerDialog()
            val args = Bundle().apply {
                putSerializable(EXTRA_DATE, date)
                /*
                date?.also {
                    putLong(EXTRA_DATE, it.atStartOfDay(ZoneId.systemDefault()).toEpochSecond())
                }
                 */
            }
            dialog.arguments = args
            return dialog
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        localDate = arguments?.getSerializable(EXTRA_DATE) as LocalDate? ?: LocalDate.now()

        val year = localDate.year
        val month = localDate.monthValue - 1
        val day = localDate.dayOfMonth

        val listener = DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
            this.localDate = LocalDate.of(year, monthOfYear + 1, dayOfMonth)
            onOk?.invoke(localDate)
        }

        val dialog = DatePickerDialog(activity!!, listener, year, month, day)
        dialog.setOnCancelListener {
            onCancel?.invoke()
        }

        return dialog
    }
}

Usage

val now = LocalDateTime.now()

val dialog = JavaDatePickerDialog.newInstance(date=now.toLocalDate())
dialog.onOk = { date ->
    // do something
}
dialog.show(supportFragmentManager, "editDate")
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.