Android Material DatePicker中的错误日期

dly7yett  于 2023-04-10  发布在  Android
关注(0)|答案(3)|浏览(136)

我试图从DatePicker中获取所选日期,但总是比所选日期少一天
例如,如果我选择14/2/2022,则获得13/2/2022,如果我选择8/10/2018,则获得7/10/2018
这是我的代码:

private fun DatePickerSelected() {
    val picker = MaterialDatePicker.Builder.datePicker()
        .setTitleText("Select date of birth")
        .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
        .build()

    picker.addOnPositiveButtonClickListener {
        val date = Date(picker.selection!!)
        Log.d("Date",date.toString())
        val dateString = SimpleDateFormat("dd/MM/yyyy").format(date)
        binding.edtBirthday.editText?.setText(dateString)
    }

    picker.show(requireActivity().supportFragmentManager, "BirthdayPicker")
}

问题出在哪里?谢谢!

wvmv3b1j

wvmv3b1j1#

我找到了使用日历的解决方案

picker.addOnPositiveButtonClickListener {
        val utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
        utc.timeInMillis = it
        //+1: The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0
        val stringData = "${utc.get(Calendar.DAY_OF_MONTH)}/${utc.get(Calendar.MONTH)+1}/${utc.get(Calendar.YEAR)}"
        binding.edtBirthday.editText?.setText(stringData)
    }
ryevplcw

ryevplcw2#

原来调用picker的结果是一个UTC时区的时间戳,你所要做的就是把它转换成你的本地时区。
下面是显示DialogPicker的逻辑,它带有一个侦听器,可以将结果从UTC转换为设备的时区:

// create the dialog picker
    val picker = MaterialDatePicker.Builder
        .datePicker()
        .setSelection(initialDate)// initial date can be a date on local timezone
        .setTitleText("")
        .build()

    picker.addOnPositiveButtonClickListener {
        // create an object with a matching timezone
        val utcDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(it), ZoneOffset.UTC)
        // create an object converting from UTC to the device´s timezone
        val myTimeZoneDate = ZonedDateTime.of(utcDate, ZoneId.systemDefault())
        // get the long timestamp to use as you want
        val myTimeZoneDateLong = myTimeZoneDate.toInstant().toEpochMilli()

    }
    
    // show picker
    picker.show(parentFragmentManager, "tag")

记住:你应该始终将Date处理为无时区,包括将其存储在数据库中,使用它来同步数据或进行比较。唯一的例外是当你向用户显示它时,在这种情况下,显然应该将其转换为本地时区。如果用户使用不同的时区使用你的应用程序,不这样做会导致真正的大问题。

xtfmy6hx

xtfmy6hx3#

试试这个代码,加一天

date.add(Calendar.DAY_OF_MONTH,1)

相关问题