addMonths method
Adds calendar months while keeping the date valid.
Example: January 31 + 1 month becomes February 28/29.
Implementation
DateTime addMonths(int months) {
final totalMonths = year * 12 + (month - 1) + months;
final targetYear = totalMonths ~/ 12;
final targetMonth = totalMonths % 12 + 1;
final lastDay = DateTime(
targetYear,
targetMonth + 1,
0,
).day;
final targetDay = day > lastDay ? lastDay : day;
return DateTime(
targetYear,
targetMonth,
targetDay,
hour,
minute,
second,
millisecond,
microsecond,
);
}