monthsBetween function

List<DateTime> monthsBetween(
  1. DateTime start,
  2. DateTime end
)

Returns the first day of each month from start through end inclusive. The day and time components of the inputs are ignored.

Example:

monthsBetween(DateTime(2020, 1, 15), DateTime(2020, 3, 1));
// [2020-01-01, 2020-02-01, 2020-03-01]

Implementation

List<DateTime> monthsBetween(DateTime start, DateTime end) {
  final List<DateTime> out = <DateTime>[];
  DateTime d = DateTime(start.year, start.month);
  final DateTime e = DateTime(end.year, end.month);
  while (!d.isAfter(e)) {
    out.add(d);
    d = DateTime(d.year, d.month + 1);
  }
  return out;
}