DatePickerDialog在Android中选择错误的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>发布于 2020-02-26 12:43:31
日期选择器是可以的,但是用于在吐司中显示日期的格式是错误的:
您必须使用dd (月中的一天),而不是DD (一年中的一天)。2月11日确实是一年中的第42天。
private val format = SimpleDateFormat("dd MMM, yyyy",Locale.US)https://stackoverflow.com/questions/60414114
复制相似问题