addMonths static method

DateTime addMonths(
  1. DateTime date,
  2. int months
)

Returns the DateTime resulting from adding the given number of months to this DateTime.

The result is computed by incrementing the month parts of this DateTime by months months, and, if required, adjusting the day part of the resulting date downwards to the last day of the resulting month.

For example: (2020, 12, 31) -> add 2 months -> (2021, 2, 28). (2020, 12, 31) -> add 1 month -> (2021, 1, 31).

Implementation

static DateTime addMonths(DateTime date, int months) {
  var res = copyWith(date, month: date.month + months);
  if (date.day != res.day) res = copyWith(res, day: 0);
  return res;
}