Home > Software design >  calculating previous months from Date() duplicates a month
calculating previous months from Date() duplicates a month

Time:05-31

I am trying to 12 previous months from today, but it displays

Date to start with - Mon May 30 22:57:30 GMT 01:00 2022

Months displayed are - these are the values in the monthsArray, Month March 2022 is displayed twice

April 2022 March 2022 (DISPLAYED TWICE) March 2022 (DISPLAYED TWICE) February 2022 January 2022 December 2021 November 2021 October 2021 September 2021 August 2021 July 2021 June 2021

This is the logic to display months

  val monthsArray: ArrayList<String> = ArrayList()
    val date = Date()
    var i = 1
    while (i <= 12) {
        date.month = date.month - 1
        monthsArray.add(readableSpinnerItemDate(date.time))
        i  
    }

Could you please suggest what might be wrong here please

Thanks R

CodePudding user response:

I think this should do what you are looking for.

val monthsArray = (0..11).map { LocalDateTime.now().minusMonths(it.toLong()).format(DateTimeFormatter.ofPattern("MMMM yyyy")) }
  • Related