index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import toDate from "../toDate/index.js";
  2. import differenceInCalendarMonths from "../differenceInCalendarMonths/index.js";
  3. import compareAsc from "../compareAsc/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. import isLastDayOfMonth from "../isLastDayOfMonth/index.js";
  6. /**
  7. * @name differenceInMonths
  8. * @category Month Helpers
  9. * @summary Get the number of full months between the given dates.
  10. *
  11. * @description
  12. * Get the number of full months between the given dates.
  13. *
  14. * ### v2.0.0 breaking changes:
  15. *
  16. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  17. *
  18. * @param {Date|Number} dateLeft - the later date
  19. * @param {Date|Number} dateRight - the earlier date
  20. * @returns {Number} the number of full months
  21. * @throws {TypeError} 2 arguments required
  22. *
  23. * @example
  24. * // How many full months are between 31 January 2014 and 1 September 2014?
  25. * var result = differenceInMonths(new Date(2014, 8, 1), new Date(2014, 0, 31))
  26. * //=> 7
  27. */
  28. export default function differenceInMonths(dirtyDateLeft, dirtyDateRight) {
  29. requiredArgs(2, arguments);
  30. var dateLeft = toDate(dirtyDateLeft);
  31. var dateRight = toDate(dirtyDateRight);
  32. var sign = compareAsc(dateLeft, dateRight);
  33. var difference = Math.abs(differenceInCalendarMonths(dateLeft, dateRight));
  34. var result; // Check for the difference of less than month
  35. if (difference < 1) {
  36. result = 0;
  37. } else {
  38. if (dateLeft.getMonth() === 1 && dateLeft.getDate() > 27) {
  39. // This will check if the date is end of Feb and assign a higher end of month date
  40. // to compare it with Jan
  41. dateLeft.setDate(30);
  42. }
  43. dateLeft.setMonth(dateLeft.getMonth() - sign * difference); // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full
  44. // If so, result must be decreased by 1 in absolute value
  45. var isLastMonthNotFull = compareAsc(dateLeft, dateRight) === -sign; // Check for cases of one full calendar month
  46. if (isLastDayOfMonth(toDate(dirtyDateLeft)) && difference === 1 && compareAsc(dirtyDateLeft, dateRight) === 1) {
  47. isLastMonthNotFull = false;
  48. }
  49. result = sign * (difference - Number(isLastMonthNotFull));
  50. } // Prevent negative zero
  51. return result === 0 ? 0 : result;
  52. }