Search code examples
androidmonthcalendar

Getting List of Month for Past 1 year in Android dynamically


Greetings of the day.

In my application, I have displayed list of months statically currently.

But, I want list of months dynamically. i.e. 12 months which are lesser or equal to current running month of current year.

For Example today is 2nd May 2020, So, List should be as below :

Jun, 2019. Jul, 2019. Aug, 2019. Sep, 2019. Oct, 2019. Nov, 2019. Dec, 2019. Jan, 2020. Feb, 2020. Mar, 2020. Apr, 2020. May, 2020.

Please guide how can I achieve this thing in Android. Thanks.


Solution

  • val formatter = SimpleDateFormat("MMM, yyyy")
    val list = arrayListOf<String>()
    Calendar.getInstance().let {
        calendar ->
        calendar.add(Calendar.MONTH, -11)
        for (i in 0 until 12) {
            list.add(formatter.format(calendar.timeInMillis))
            calendar.add(Calendar.MONTH, 1)
        }
    }
    print(list)