2

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!

Sergio
  • 725
  • 1
  • 7
  • 20
  • Avoid using the Date and Calendar classes. They are considered obsolete in Java because there are a number of issues that make them difficult and error-prone to work with. Use LocalDateTime and ZonedDateTime instead. – Tenfour04 Mar 06 '21 at 20:36
  • I know @Tenfour04 but for this project, I am not able to use these libraries so I need to find a solution using `java.util` libraries. – Sergio Mar 06 '21 at 21:03
  • Hello. I have the same problem, did you find a solution for this and can you help me? – esantiago Jul 30 '22 at 05:12

0 Answers0