Create DatePicker in Kotlin

In this Kotlin code example we will learn how to create DatePicker in Kotlin programmatically. To break it in more details the code example below will cover: 

  • Create DatePicker in LinearLayout
  • Initialize DatePicker with current date( Year, Month and Day)
  • When user changes the DatePicker values, call OnDateChangeListener and get input from the DatePicker
  • Set DatePicker values like Year, Month and Day into a TextView

XML Layout File

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""


Create DatePicker In Kotlin Programmatically. Code Example.

import android.os.Build
import android.os.Bundle
import android.widget.DatePicker
import android.widget.LinearLayout
import android.widget.TextView
import java.util.*

class DatePickerExample : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        val linearLayout = findViewById( as LinearLayout

        val textView = TextView(this)


        val datePicker = DatePicker(this)
        textView.text = "Year: "+datePicker.year+ " Month: "+ (datePicker.month+1) +" Day: "+ datePicker.dayOfMonth

        val calendar = Calendar.getInstance()
        calendar.timeInMillis = System.currentTimeMillis()

        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
                DatePicker.OnDateChangedListener { datePicker, year, month, day->
            textView.text = "Year: "+ year + " Month: "+ (month+1) + " Day: "+day


If you run this Kotlin code example you should get the view as on the picture below. The text line above the calendar view displays the selected Year, Month and Day. Users can tap on a different day or choose a different month or even a year.

DatePicker Example In Kotlin
DatePicker Example In Kotlin

I hope this example was helpful!

If you are looking for more code examples in Kotlin or even longer step by step Kotlin tutorials, checkout the Android->Kotlin category of this blog.

And if you are looking for books or video tutorials on Kotlin check the list of resources below. I hope you will find some of them helpful!

Happy learning Kotlin!

Building Mobile Apps with Kotlin for Android – Books

Building Mobile Apps with Kotlin for Android – Video Courses

Leave a Reply

Your email address will not be published. Required fields are marked *