Home > Blockchain >  How to make a list of Months along with Year (for eg. January 2022, February 2022) from a given Date
How to make a list of Months along with Year (for eg. January 2022, February 2022) from a given Date

Time:02-11

I am trying to prepare a list of Months with Years, such as below:

monthYearList = ["December 2021", "January 2022", "February 2022"]

I have a date given, say: date = "2021-10-25" . Date Format is yyyy-MM-dd.

Now how to prepare the data for all the Months along with Years from this given date until the current month in a List.

Expected Output: monthYearList = ["October 2021", "November 2021", "December 2021", "January 2022", "February 2022"]

Such that it's in non-decreasing order as per month progression.

"November 2021", "December 2021" comes before "January 2022" only until the current month.

I am new to Flutter, and don't have much idea how to work with Dates in dart.

CodePudding user response:

Check this out:


List<String> getMonthsFromDayTillNow(String day) {
  // 2021-10-
  List<String> dateSplit = day.split("-");
  DateTime loopDateTime =
      DateTime(int.parse(dateSplit[0]), int.parse(dateSplit[1]), 28);
  DateTime currentDateTime = DateTime.now();
  List<String> months = [];
  while (loopDateTime.isBefore(currentDateTime)) {
    months.add("${getMonth(loopDateTime.month)} ${loopDateTime.year}");
    loopDateTime = loopDateTime.add(Duration(days: 5));
    loopDateTime = DateTime(loopDateTime.year, loopDateTime.month, 28);
  }
  months.add("${getMonth(currentDateTime.month)} ${currentDateTime.year}");
  return months;
}

String getMonth(int monthNumber) {
  late String month;
  switch (monthNumber) {
    case 1:
      month = "January";
      break;
    case 2:
      month = "February";
      break;
    case 3:
      month = "March";
      break;
    case 4:
      month = "April";
      break;
    case 5:
      month = "May";
      break;
    case 6:
      month = "June";
      break;
    case 7:
      month = "July";
      break;
    case 8:
      month = "August";
      break;
    case 9:
      month = "September";
      break;
    case 10:
      month = "October";
      break;
    case 11:
      month = "November";
      break;
    case 12:
      month = "December";
      break;
  }
  return month;
}

Output:

void main() {
  print(getMonthsFromDayTillNow("2021-10-5")); //[October 2021, November 2021, December 2021, January 2022, February 2022]

}
  • Related