I need to set the Date in the material date picker. It requires Long
to set the date. I tried to do it with:
val formatter = DateTimeFormatter.ofPattern(DAY_FORMAT_PATTERN)
val selectedDate = LocalDate.parse(viewModel.selectedDateStateFlow.value, formatter)
val selectedDateToLong = selectedDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
val datePicker = MaterialDatePicker.Builder.datePicker()
.setTheme(R.style.DatePicker)
.setSelection(selectedDateToLong)
.build()
in this case date picker sets the date one day less. Is there a more accurate conversion option?
for example:
I/System.out: viewModel.selectedDateStateFlow.value = 30 Nov, 2021
I/System.out: selectedDate = 2021-11-30
I/System.out: selectedDateToLong = 1638219600000
I/System.out: MaterialDatePicker.todayInUtcMilliseconds() = 1638230400000
but date picker set "Nov 29, 2021"
the timezone on phone GMT+03:00 Moscow Standard Time
UPD
Compared the value of my conversion of the LocalDate
into Long
and MaterialDatePicker.todayInUtcMilliseconds()
. Received different values. What is the mistake of my translation?
UPD2.
The kind people in the comments were right about a possible error due to using a different time zone. On the advice of one of them, I tried:
val selectedDateToLong = selectedDate.atStartOfDay(ZoneOffset.UTC)...
instead of
val selectedDateToLong = selectedDate.atStartOfDay(ZoneId.systemDefault())...
It helped me