addMonths method

DateTime addMonths(
  1. int months
)

Add months to this DateTime

Example:

final date = DateTime(2023, 12, 25);
print(date.addMonths(2)); // 2024-02-25

Implementation

DateTime addMonths(int months) {
  int newMonth = month + months;
  int newYear = year;

  while (newMonth > 12) {
    newMonth -= 12;
    newYear++;
  }
  while (newMonth < 1) {
    newMonth += 12;
    newYear--;
  }

  return DateTime(
    newYear,
    newMonth,
    day,
    hour,
    minute,
    second,
    millisecond,
    microsecond,
  );
}