getMonth static method

Month getMonth(
  1. DateTime? minDate,
  2. DateTime? maxDate,
  3. int monthPage,
  4. bool up, {
  5. bool startWeekWithSunday = false,
})

generates a Month object from the Nth index from the startdate

Implementation

static Month getMonth(
  DateTime? minDate,
  DateTime? maxDate,
  int monthPage,
  bool up, {
  bool startWeekWithSunday = false,
}) {
  // if no start date is provided use the current date
  DateTime startDate = (minDate ?? DateTime.now()).removeTime();

  // if this is not the first month in this calendar then calculate a new
  // start date for this month
  if (monthPage > 0) {
    if (up) {
      // fetsch up: month will be subtructed
      startDate = DateTime(startDate.year, startDate.month - monthPage, 1);
    } else {
      // fetch down: month will be added
      startDate = DateTime(startDate.year, startDate.month + monthPage, 1);
    }
  }

  // find the first day of the first week in this month
  final weekMinDate = _findDayOfWeekInMonth(
    startDate,
    getWeekDay(startDate, startWeekWithSunday),
    startWeekWithSunday: startWeekWithSunday,
  );

  // every week has a start and end date, calculate them once for the start
  // of the month then reuse these variables for every other week in
  // month
  DateTime firstDayOfWeek = weekMinDate;
  DateTime lastDayOfWeek = _lastDayOfWeek(weekMinDate, startWeekWithSunday);

  List<Week> weeks = [];

  // we don't know when this month ends until we reach it, so we have to use
  // an indefinate loop
  while (true) {
    // if an endDate is provided we need to check if the current week extends
    // beyond this date. if it does, cap the week to the endDate and stop the
    // loop

    if (up) {
      // fetching up
      Week week;
      if (maxDate != null && firstDayOfWeek.isBefore(maxDate)) {
        week = Week(maxDate, lastDayOfWeek);
      } else {
        week = Week(firstDayOfWeek, lastDayOfWeek);
      }

      if (maxDate != null && lastDayOfWeek.isSameDayOrAfter(maxDate)) {
        weeks.add(week);
      } else if (maxDate == null) {
        weeks.add(week);
      }
      if (week.isLastWeekOfMonth) break;
    } else {
      // fetching down
      if (maxDate != null && lastDayOfWeek.isSameDayOrAfter(maxDate)) {
        Week week = Week(firstDayOfWeek, maxDate);
        weeks.add(week);
        break;
      }

      Week week = Week(firstDayOfWeek, lastDayOfWeek);
      weeks.add(week);

      if (week.isLastWeekOfMonth) break;
    }

    firstDayOfWeek = lastDayOfWeek.nextDay;
    lastDayOfWeek = _lastDayOfWeek(firstDayOfWeek, startWeekWithSunday);
  }

  return Month(weeks);
}