isAnnualDateInRange method

  1. @useResult
bool isAnnualDateInRange(
  1. DateTimeRange<DateTime>? range, {
  2. bool isInclusive = true,
})

Returns true if this DateTime is within the specified range.

When year is 0, this method checks if the month/day combination falls within the range for ANY year covered by the range. This correctly handles ranges that span year boundaries (e.g., Dec 2023 to Feb 2024).

If isInclusive is true (default), the start and end dates of the range are included in the check. Returns true if range is null. Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
bool isAnnualDateInRange(DateTimeRange? range, {bool isInclusive = true}) {
  if (range == null) {
    return true;
  }

  if (year == 0) {
    for (int checkYear = range.start.year; checkYear <= range.end.year; checkYear++) {
      final DateTime dateInYear = DateTime(checkYear, month, day);

      // Skip years where this annual date does not exist: e.g. Feb 29 in a
      // non-leap year, which DateTime silently normalizes to Mar 1. Testing
      // the rolled-over Mar 1 would give a false match.
      if (dateInYear.month != month || dateInYear.day != day) {
        continue;
      }

      if (dateInYear.isBetween(
        range.start,
        range.end,
        isInclusive: isInclusive,
      )) {
        return true;
      }
    }

    return false;
  }

  return isBetweenRange(range, isInclusive: isInclusive);
}