isAnnualDateInRange method
Checks if the current DateTime is within the specified range, considering all years in the range if the current year is 0.
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).
Args:
range (DateTimeRange?): The range to check against. Returns true if null.
inclusive (bool): If true (default), the start and end dates of the range
are included in the check. If false, only dates strictly between start
and end are considered in range.
Returns:
bool: true if the DateTime is within the range, false otherwise.
Example:
// Range spanning year boundary: Dec 15, 2023 to Feb 15, 2024
final range = DateTimeRange(
start: DateTime(2023, 12, 15),
end: DateTime(2024, 2, 15),
);
// January 10 with year=0 should be in range
DateTime(0, 1, 10).isAnnualDateInRange(range); // true
// March 10 with year=0 should NOT be in range
DateTime(0, 3, 10).isAnnualDateInRange(range); // false
Implementation
bool isAnnualDateInRange(DateTimeRange? range, {bool inclusive = true}) {
if (range == null) {
return true;
}
if (year == 0) {
// If year is 0, check if the month and day fall within the range for
// any year covered by the range.
//
// We need to handle ranges that span year boundaries correctly.
// For example, a range from Dec 2023 to Feb 2024 should include Jan 15.
// Check each year in the range to see if our month/day falls within it
for (int checkYear = range.start.year; checkYear <= range.end.year; checkYear++) {
// Create a date with our month/day in this year
final DateTime dateInYear = DateTime(checkYear, month, day);
// Check if this date falls within the range
if (dateInYear.isBetween(range.start, range.end, inclusive: inclusive)) {
return true;
}
}
return false;
}
// If year is provided, use it for comparison
return isBetweenRange(range, inclusive: inclusive);
}