countMonths method

int countMonths(
  1. DateTime? differenceDateTime
)

Calculates the number of months between the current DateTime object and differenceDateTime.

This function rounds to the nearest month and returns the count as an integer. The result can be positive if differenceDateTime is after the current DateTime object, or negative if differenceDateTime is before the current DateTime object.

Example:

DateTime startDate = DateTime(1996, 1, 1);
DateTime endDate = DateTime(2023, 10, 16);

int monthsDifference = startDate.countMonths(endDate); // Output: 334

Implementation

int countMonths(DateTime? differenceDateTime) {
  int difference =
      (differenceDateTime ?? DateTime.now()).millisecondsSinceEpoch -
          millisecondsSinceEpoch;
  int count = (difference / 2628003000).round();
  return count;
}