addOrSubtractMonths method

DateTime addOrSubtractMonths(
  1. int months
)

Adds or subtracts the specified number of months from this DateTime. Using a positive value (e.g., 1) adds months, while a negative value (e.g., -1) subtracts months.

Implementation

DateTime addOrSubtractMonths(int months) {
  final totalMonths = month + months;
  var newYear = year + (totalMonths ~/ 12);
  var newMonth = totalMonths % 12;

  // Handle the case where totalMonths is a multiple of 12 (e.g., adding/subtracting 12, 24, etc. months)
  if (newMonth == 0) {
    newMonth = 12;
    newYear -=
        1; // Adjust the year if we "wrapped around" to December of the previous year
  }

  var newDay = day;
  // Adjust the day if it exceeds the number of days in the new month
  while (newDay > DateTime(newYear, newMonth + 1, 0).day) {
    newDay--;
  }
  return DateTime(
    newYear,
    newMonth,
    newDay,
    hour,
    minute,
    second,
    millisecond,
    microsecond,
  );
}