differenceInCalendarMonths.mjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { toDate } from "./toDate.mjs";
  2. /**
  3. * @name differenceInCalendarMonths
  4. * @category Month Helpers
  5. * @summary Get the number of calendar months between the given dates.
  6. *
  7. * @description
  8. * Get the number of calendar months between the given dates.
  9. *
  10. * @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).
  11. *
  12. * @param dateLeft - The later date
  13. * @param dateRight - The earlier date
  14. *
  15. * @returns The number of calendar months
  16. *
  17. * @example
  18. * // How many calendar months are between 31 January 2014 and 1 September 2014?
  19. * const result = differenceInCalendarMonths(
  20. * new Date(2014, 8, 1),
  21. * new Date(2014, 0, 31)
  22. * )
  23. * //=> 8
  24. */
  25. export function differenceInCalendarMonths(dateLeft, dateRight) {
  26. const _dateLeft = toDate(dateLeft);
  27. const _dateRight = toDate(dateRight);
  28. const yearDiff = _dateLeft.getFullYear() - _dateRight.getFullYear();
  29. const monthDiff = _dateLeft.getMonth() - _dateRight.getMonth();
  30. return yearDiff * 12 + monthDiff;
  31. }
  32. // Fallback for modularized imports:
  33. export default differenceInCalendarMonths;