androiddatetimekotlincalendarjava.util.calendar

How to add dates to calender in the right way


I have an ArrayList that contains date - [1, 5, 2020] // day|month|year

I am adding this to calendar in this way:

calendar.add(Calendar.DAY_OF_MONTH, dateList[0])
calendar.add(Calendar.MONTH, dateList[1])
calendar.add(Calendar.YEAR, dateList[2])

But when I try to assign this to my date picker, I am getting this date:

datePicker.maxDate = calendar
date picker Log: 16/10/4040

What could be the problem with my code?


Solution

  • That's because you ADD those values (to the initial date when it was instantiated). Instead you should use set.

    calendar.set(Calendar.DAY_OF_MONTH, dateList[0])
    calendar.set(Calendar.MONTH, dateList[1])
    calendar.set(Calendar.YEAR, dateList[2])