Home > Software design >  How to label each date on dart using logic?
How to label each date on dart using logic?

Time:09-22

I am trying to label the date as shown in the photo. After the first Sunday is passed, the number labeled reaches the 20s. After the 2nd Sunday is passed, the number labeled reaches the 30s. The number behind represents the day of the week. Eg. 25 represents the second Friday of the month.

Any suggestion on how to create this logic?

enter image description here

CodePudding user response:

You can achieve this using the DateTime class. I've added a sample implementation, which you can further optimise:

// Function that maps day with corresponding value
Map<int, int> generateMap(DateTime firstDateOfMonth) {
  final map       = <int, int>{};
  final numOfDays = getNumberOfDaysInMonth(firstDateOfMonth);
  int weekDay     = firstDateOfMonth.weekday;
  int sunday      = (7 - weekDay)   1;
  int week        = 1;
  
  for (int i = 1; i <= numOfDays; i  ) {
    if (sunday < i) {
      weekvv  = 1;
      sunday  = 7;
      weekDay = 1;
    }
    map[i] = (week * 10)   weekDay;
    weekDay  ;
  }

  return map;
}

// Returns Number of days in a month
int getNumberOfDaysInMonth(DateTime date) {
  int numOfDays = 0;
  switch (date.month) {
    case DateTime.january:
    case DateTime.march:
    case DateTime.may:
    case DateTime.july:
    case DateTime.august:
    case DateTime.october:
    case DateTime.december:
      numOfDays = 31;
      break;
    case DateTime.april:
    case DateTime.june:
    case DateTime.september:
    case DateTime.november:
      numOfDays = 30;
      break;
    case DateTime.february:
      isLeapYear(date) ? 29 : 28;
      break;
  }
  return numOfDays;
}

// Checks whether the year is Leap Year
bool isLeapYear(DateTime date) => date.year % 4 == 0;

You can pass the first day of the month to generate the mapping for that particular month:

final now = DateTime.now();
final firstDayOfMonth = DateTime(now.year, now.month);

print(generateMap(firstDayOfMonth));

For the current month (Sept 2021), it prints out the following output:

{
1: 13, 2: 14, 3: 15, 4: 16, 5: 17,
6: 21, 7: 22, 8: 23, 9: 24, 10: 25,
11: 26, 12: 27, 13: 31, 14: 32, 15: 33,
16: 34, 17: 35, 18: 36, 19: 37, 20: 41,
21: 42, 22: 43, 23: 44, 24: 45, 25: 46,
26: 47, 27: 51, 28: 52, 29: 53, 30: 54
}
  • Related