java - 为什么这段代码在 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>
解决方案
日期选择器正常,但用于在 toast 中显示日期的格式错误:
您必须使用dd
(day in month),而不是DD
(day in year)。2 月 11 日确实是一年中的第 42 天。
private val format = SimpleDateFormat("dd MMM, yyyy",Locale.US)
推荐阅读
- angular - @angular/forms 和 ng-packagr
- python - 在精灵中向前移动
- python-2.7 - MySQLdb commit() 方法不保存数据
- git - 仅在 VSTS 发布管道中下载对 git repo 的更改
- bash - 在 BASH 配置文件中定义变量的最佳实践
- mobile - 无论手指在虚幻中的位置如何,同时调用捏和旋转事件?
- java - 如何从 postgres db 打印 Java 中的时间戳值?
- ksh - 调用函数时陷阱未激活
- php - 如何将 php 文件导入控制器并收集数据
- django - name_file/Scripts/activate 'name_file' 未被识别为内部或外部命令、可运行程序或批处理文件 windows 10