0
votes

I am trying to get all the months from user created date to future 6 months. Suppose user is created in October 2020 then I need all the months in list from October 2020 to January 2021(current month) plus next 6 months. I tried below but getting wrong output.

static List<String> getMonthsInYear(){
  List<String> years=[];
  DateFormat dateFormat=DateFormat("MMM yyyy");
  DateTime createdDate = DateTime(2020,10,1,0,0,0,0,0);

  DateTime today = DateTime.now();
  var i=0,currentMonth=1;
  while(today.year==createdDate.year && today.month==createdDate.month){
    createdDate=DateTime(createdDate.year,createdDate.month+i,1,0,0,0,0,0);
    years.add(dateFormat.format(createdDate));
    i++;
  }
  while(currentMonth<7){
    createdDate=DateTime(createdDate.year,createdDate.month+currentMonth,1,0,0,0,0,0);
    years.add(dateFormat.format(createdDate));
    currentMonth++;
  }
  print("BLB createdDate ${years}");
  return years;
}

My output is [Nov 2020, Jan 2021, Apr 2021, Aug 2021, Jan 2022, Jul 2022].

But I wanted my output to be [Oct 2020, Nov 2020, Dec 2020, Jan 2021, Feb 2021, Mar 2021, Apr 2021, May 2021, Jun 2021] Can someone help me.

3

3 Answers

1
votes

This should give you what you want:

static List<String> getMonthsInYear(DateTime userCreatedDate) {
    final dates = <String>[];
    final now = DateTime.now();
    final sixMonthFromNow = DateTime(now.year, now.month+6);
    DateTime date = userCreatedDate;

    while (date.isBefore(sixMonthFromNow)) {
      dates.add(dateFormat.format(date));
      date = DateTime(date.year, date.month+1);
    }
    return dates;
  }
}
0
votes

This should give you what you want:

  static List<String> getMonthsInYear(DateTime userCreatedDate) {
    DateFormat dateFormat=DateFormat("MMM yyyy");

    return List.generate(6, (int index) {
      final date = DateTime(userCreatedDate.year, userCreatedDate.month + index);
      return dateFormat.format(date);
    });
  }
0
votes

I don't know why that's your output of the next 6 months.

[Oct 2020, Nov 2020, Dec 2020, Jan 2021, Feb 2021, Mar 2021, Apr 2021, May 2021, Jun 2021]

If the output you want is this

[Oct 2020, Nov 2020, Dec 2020, Jan 2021, Feb 2021, Mar 2021]

the code looks like this:

  static List<String> getMonthsInYear(DateTime createdDate, int length){
    DateFormat dateFormat=DateFormat("MMM yyyy");

    List<String> years=[];

    int currentYear = createdDate.year;
    int currentMonth = createdDate.month;
    for(int i=0; i<length; i++) {
      createdDate=DateTime(currentYear, currentMonth + i);
      years.add(dateFormat.format(createdDate));

      if(currentMonth + i == 1) {
        currentYear += 1;
      }
    }
    return years;
  }

usage code :

DateTime createdDate = DateTime(2020,10,1,0,0,0,0,0);
print(getMonthsInYear(createdDate, 6));