0

I'm looking for a way to get the number of weeks with X weekday in them a month has. For example:- How many weeks are there in march with Wednesday in them? Answer - 5.

I would be happy with a general answer but it would be great to know if there's an efficient way to do that using dart. Thank you.

Deepanshu
  • 890
  • 5
  • 18
  • Also see https://stackoverflow.com/q/67183678/ for a similar question. The answer there should be fairly easily adaptable to do what you want. – jamesdlin Jun 25 '21 at 07:05

1 Answers1

1

Try this...

int weeksCountOfWeekday(int weekdayToCnt, int month, int year) {
  assert(weekdayToCnt >= 1 && weekdayToCnt <= 7);

  final DateTime startDate = DateTime(year, month);
  final DateTime endDate =
      DateTime(year, month + 1).subtract(const Duration(days: 1));
  
  int res = 1;
  int dayOfWeekday;
  
  if (weekdayToCnt < startDate.weekday) {
    dayOfWeekday = startDate.day + 7 - (startDate.weekday - weekdayToCnt);
  } else {
    dayOfWeekday = 1 + weekdayToCnt - startDate.weekday;
  }

  while (dayOfWeekday + 7 <= endDate.day) {
    res++;
    dayOfWeekday += 7;
  }

  return res;
}
rickimaru
  • 2,275
  • 9
  • 13