How it works MaterialDatePicker in Android?

367 Views Asked by At

I have some doubts about how it works the Calendar library in Android.

I have implemented a listener to get the selected date in the MaterialDatePicker. With the method addOnPositiveButtonClickListener, I get the date selected in milliseconds but I need to transform these milliseconds to a Date object, BUT! whenever I transform this millisecond to a Date object, I am not getting the right value.

For example, if I select 03/24/2021, when I create a new Date object with the correspondent millisecond I get the next Date -> 03/23/2021.

I am trying different solutions I find in different posts but no one works fine for me.

I am trying to use Calendar but is not working properly either.

fun Long.toDate() : Date {
 val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
 calendar.timeInMillis = this // calendar.time.time = this
 return calendar.time
 }

and also try it out with different timeZone

fun Long.toDate() : Date {
 val calendar = Calendar.getInstance(TimeZone.getDefault())
 calendar.timeInMillis = this // calendar.time.time = this
 return calendar.time
 }

I have also try to save the millisecond on my Calendar instance with calendar.time.time but also is not working for me.

It is so curious because if I set the next values on my device:

  • Time zone in New Zealand (GMT+13:45) at 10:00 AM,
  • I select 03/02/2021, so should return the same date.
  • For this specific example is working fine (I am in Madrid, Spain GMT+01:00) and is returning the date 03/02/2021.

If it was working bad, should returns 02/02/2021, but for this timeZone is working fine.

But, if I change my device values to:

  • Time zone to Colombia (GMT-05:00) and I set my device time to 10:00 PM.
  • I select the same date, 03/02/2021, it should return the same date.
  • In this case, is returning me the day before, 03/01/2021.

Why MaterialDatePicker is working so bad and how can I fix that without doing so badly tricky code?

I saw it can be fixed used SimpleDateformat, but I would like to keep the timeZone and do it a good way, or at least the best way...

Thanks in advance!

0

There are 0 best solutions below