occurrence static method

DateTime occurrence(
  1. DateTime anchor,
  2. URepeat repeat,
  3. URepeatCalendar calendar,
  4. int k,
)

The k-th occurrence counted from anchor; days past a month's end clamp to its last day.

Implementation

static DateTime occurrence(DateTime anchor, URepeat repeat, URepeatCalendar calendar, int k) {
  switch (repeat) {
    case URepeat.none:
      return anchor;
    case URepeat.minute:
      return anchor.add(Duration(minutes: k));
    case URepeat.hourly:
      return anchor.add(Duration(hours: k));
    case URepeat.daily:
      return DateTime(anchor.year, anchor.month, anchor.day + k, anchor.hour, anchor.minute, anchor.second);
    case URepeat.weekly:
      return DateTime(anchor.year, anchor.month, anchor.day + 7 * k, anchor.hour, anchor.minute, anchor.second);
    case URepeat.monthly:
    case URepeat.yearly:
      final int months = repeat == URepeat.monthly ? k : 12 * k;
      if (calendar == URepeatCalendar.persian) {
        final UJalali j = UJalali.fromDateTime(anchor);
        final int index = j.year * 12 + (j.month - 1) + months;
        final int year = index ~/ 12;
        final int month = index % 12 + 1;
        final int last = month <= 6 ? 31 : (month <= 11 ? 30 : (UJalali(year).isLeapYear() ? 30 : 29));
        return UJalali(year, month, j.day > last ? last : j.day, anchor.hour, anchor.minute, anchor.second).toDateTime();
      }
      final int index = anchor.year * 12 + (anchor.month - 1) + months;
      final int year = index ~/ 12;
      final int month = index % 12 + 1;
      final int last = DateTime(year, month + 1, 0).day;
      return DateTime(year, month, anchor.day > last ? last : anchor.day, anchor.hour, anchor.minute, anchor.second);
  }
}