differenceInMonths.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use strict";
  2. exports.differenceInMonths = differenceInMonths;
  3. var _index = require("./compareAsc.js");
  4. var _index2 = require("./differenceInCalendarMonths.js");
  5. var _index3 = require("./isLastDayOfMonth.js");
  6. var _index4 = require("./toDate.js");
  7. /**
  8. * @name differenceInMonths
  9. * @category Month Helpers
  10. * @summary Get the number of full months between the given dates.
  11. *
  12. * @description
  13. * Get the number of full months between the given dates using trunc as a default rounding method.
  14. *
  15. * @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).
  16. *
  17. * @param dateLeft - The later date
  18. * @param dateRight - The earlier date
  19. *
  20. * @returns The number of full months
  21. *
  22. * @example
  23. * // How many full months are between 31 January 2014 and 1 September 2014?
  24. * const result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31))
  25. * //=> 7
  26. */
  27. function differenceInMonths(dateLeft, dateRight) {
  28. const _dateLeft = (0, _index4.toDate)(dateLeft);
  29. const _dateRight = (0, _index4.toDate)(dateRight);
  30. const sign = (0, _index.compareAsc)(_dateLeft, _dateRight);
  31. const difference = Math.abs(
  32. (0, _index2.differenceInCalendarMonths)(_dateLeft, _dateRight),
  33. );
  34. let result;
  35. // Check for the difference of less than month
  36. if (difference < 1) {
  37. result = 0;
  38. } else {
  39. if (_dateLeft.getMonth() === 1 && _dateLeft.getDate() > 27) {
  40. // This will check if the date is end of Feb and assign a higher end of month date
  41. // to compare it with Jan
  42. _dateLeft.setDate(30);
  43. }
  44. _dateLeft.setMonth(_dateLeft.getMonth() - sign * difference);
  45. // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full
  46. // If so, result must be decreased by 1 in absolute value
  47. let isLastMonthNotFull =
  48. (0, _index.compareAsc)(_dateLeft, _dateRight) === -sign;
  49. // Check for cases of one full calendar month
  50. if (
  51. (0, _index3.isLastDayOfMonth)((0, _index4.toDate)(dateLeft)) &&
  52. difference === 1 &&
  53. (0, _index.compareAsc)(dateLeft, _dateRight) === 1
  54. ) {
  55. isLastMonthNotFull = false;
  56. }
  57. result = sign * (difference - Number(isLastMonthNotFull));
  58. }
  59. // Prevent negative zero
  60. return result === 0 ? 0 : result;
  61. }