Why this code pick wrong dayofMonth in kotlin(Android)?

Gurarshdeep Singh :

DatePickerDialog in Android pick wrong dayofMonth else coding is running fine

If I select 11 FEB 2020 ....Toast Shows 42 FEB 2020 ...... Problem is with dayofMonth only

This is MainActivity.kt

class MainActivity : AppCompatActivity() {
    private val format = SimpleDateFormat("DD MMM, YYYY",Locale.US)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_show.setOnClickListener {
            val now = Calendar.getInstance()
            val datePicker = DatePickerDialog(this,DatePickerDialog.OnDateSetListener{ view, year, month, dayOfMonth ->

                val selectedDate = Calendar.getInstance()
                selectedDate.set(Calendar.YEAR, year)
                selectedDate.set(Calendar.MONTH, month)
                selectedDate.set(Calendar.DAY_OF_MONTH, dayOfMonth)

                val date = format.format(selectedDate.time)

                Toast.makeText(this,"Date: $date",Toast.LENGTH_SHORT).show()
            },
                now.get(Calendar.YEAR),now.get(Calendar.MONTH),now.get(Calendar.DAY_OF_MONTH))

            datePicker.show()
        }
    }
}

This is activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Benoit :

The date picker is OK but the format used to display the date in the toast is wrong:

You must use dd (day in month), rather than DD (day in year). 11 FEB is indeed the 42nd day of the year.

private val format = SimpleDateFormat("dd MMM, yyyy",Locale.US)

Reference

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=8125&siteId=1