differenceInCalendarMonths.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. "use strict";
  2. exports.differenceInCalendarMonths = differenceInCalendarMonths;
  3. var _index = require("./toDate.js");
  4. /**
  5. * @name differenceInCalendarMonths
  6. * @category Month Helpers
  7. * @summary Get the number of calendar months between the given dates.
  8. *
  9. * @description
  10. * Get the number of calendar months between the given dates.
  11. *
  12. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  13. *
  14. * @param dateLeft - The later date
  15. * @param dateRight - The earlier date
  16. *
  17. * @returns The number of calendar months
  18. *
  19. * @example
  20. * // How many calendar months are between 31 January 2014 and 1 September 2014?
  21. * const result = differenceInCalendarMonths(
  22. * new Date(2014, 8, 1),
  23. * new Date(2014, 0, 31)
  24. * )
  25. * //=> 8
  26. */
  27. function differenceInCalendarMonths(dateLeft, dateRight) {
  28. const _dateLeft = (0, _index.toDate)(dateLeft);
  29. const _dateRight = (0, _index.toDate)(dateRight);
  30. const yearDiff = _dateLeft.getFullYear() - _dateRight.getFullYear();
  31. const monthDiff = _dateLeft.getMonth() - _dateRight.getMonth();
  32. return yearDiff * 12 + monthDiff;
  33. }