Android Date Picker Dialog With Java Time (Kotlin)

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")

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.