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]

Audited: 2026-06-12 11:26 EDT

Implementation

List<DateTime> monthsBetween(DateTime start, DateTime end) {
  final List<DateTime> out = <DateTime>[];
  // Both bounds are truncated to the first of the month (local time) so that the
  // inputs' day and time components cannot affect the loop comparison.
  // ignore: saropa_lints/avoid_datetime_constructor -- year/month from a valid DateTime; the omitted day defaults to 1, which exists in every month
  DateTime d = DateTime(start.year, start.month);
  // ignore: saropa_lints/avoid_datetime_constructor -- year/month from a valid DateTime; the omitted day defaults to 1, which exists in every month
  final DateTime e = DateTime(end.year, end.month);
  while (!d.isAfter(e)) {
    out.add(d);
    // Step one calendar month; month 13 rolls over to January of the next year.
    // ignore: saropa_lints/avoid_datetime_constructor, saropa_lints/avoid_datetime_constructor_unvalidated -- month + 1 with the day omitted is always the 1st of the next month; December rolling to January is intended
    d = DateTime(d.year, d.month + 1);
  }
  return out;
}