'wrong day in Android Material DatePicker

i'm trying to get te selected date from DatePicker but always i have one day less than the selected

For example, if I select 14/2/2022 i obtain 13/2/2022 and if I select 8/10/2018 i obtain 7/10/2018

This is my code:

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")
}

Which is the problem? Thanks!



Solution 1:[1]

I found the solution using calendar

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)
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Electrocode