首页 > 解决方案 > 为什么这段代码在 kotlin(Android) 中选择了错误的 dayofMonth?

问题描述

Android中的DatePickerDialog选择错误的dayofMonth,否则编码运行良好

如果我选择 2020 年 2 月 11 日 ....Toast 显示 2020 年 2 月 42 日 ......问题仅出在 dayofMonth

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

这是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>

标签: javaandroidkotlin

解决方案


日期选择器正常,但用于在 toast 中显示日期的格式错误:

您必须使用dd(day in month),而不是DD(day in year)。2 月 11 日确实是一年中的第 42 天。

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

参考


推荐阅读