monthDifference property

int get monthDifference

The difference in months between the start and end dates of this range.

This calculates the absolute difference in years, multiplies by 12, and then adds the difference in months. It handles cases where the start and end dates are in different years or have different days of the month.

Example:

final range = DateTimeRange(start: DateTime(2024, 1, 1), end: DateTime(2025, 6, 1));
print(range.monthDifference); // Output: 17

Implementation

int get monthDifference {
  var months = ((start.year - end.year).abs() - 1) * 12;
  months += end.month + (12 - start.month);
  return months;
}