addMonths method

  1. @override
Gregorian addMonths(
  1. int months
)
override

Makes a new date object with added months to this date

Original date object remains unchanged

This method is NOT safe for day being out of month length, But is safe for month overflow

Throws DateException on problems

Implementation

@override
Gregorian addMonths(int months) {
  if (months == 0) {
    return this;
  } else {
    // this is fast enough, no need for further optimization
    final int sum = month + months - 1;
    final int mod = sum % 12;
    // can not use "sum ~/ 12" directly
    final int deltaYear = (sum - mod) ~/ 12;

    return Gregorian(
      year + deltaYear,
      mod + 1,
      day,
      hour,
      minute,
      second,
      millisecond,
    );
  }
}