differenceInMonths.cjs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict";
  2. exports.differenceInMonths = differenceInMonths;
  3. var _index = require("./_lib/normalizeDates.cjs");
  4. var _index2 = require("./compareAsc.cjs");
  5. var _index3 = require("./differenceInCalendarMonths.cjs");
  6. var _index4 = require("./isLastDayOfMonth.cjs");
  7. /**
  8. * The {@link differenceInMonths} function options.
  9. */
  10. /**
  11. * @name differenceInMonths
  12. * @category Month Helpers
  13. * @summary Get the number of full months between the given dates.
  14. *
  15. * @param laterDate - The later date
  16. * @param earlierDate - The earlier date
  17. * @param options - An object with options
  18. *
  19. * @returns The number of full months
  20. *
  21. * @example
  22. * // How many full months are between 31 January 2014 and 1 September 2014?
  23. * const result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31))
  24. * //=> 7
  25. */
  26. function differenceInMonths(laterDate, earlierDate, options) {
  27. const [laterDate_, workingLaterDate, earlierDate_] = (0,
  28. _index.normalizeDates)(options?.in, laterDate, laterDate, earlierDate);
  29. const sign = (0, _index2.compareAsc)(workingLaterDate, earlierDate_);
  30. const difference = Math.abs(
  31. (0, _index3.differenceInCalendarMonths)(workingLaterDate, earlierDate_),
  32. );
  33. if (difference < 1) return 0;
  34. if (workingLaterDate.getMonth() === 1 && workingLaterDate.getDate() > 27)
  35. workingLaterDate.setDate(30);
  36. workingLaterDate.setMonth(workingLaterDate.getMonth() - sign * difference);
  37. let isLastMonthNotFull =
  38. (0, _index2.compareAsc)(workingLaterDate, earlierDate_) === -sign;
  39. if (
  40. (0, _index4.isLastDayOfMonth)(laterDate_) &&
  41. difference === 1 &&
  42. (0, _index2.compareAsc)(laterDate_, earlierDate_) === 1
  43. ) {
  44. isLastMonthNotFull = false;
  45. }
  46. const result = sign * (difference - +isLastMonthNotFull);
  47. return result === 0 ? 0 : result;
  48. }