index.js 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name differenceInCalendarMonths
  5. * @category Month Helpers
  6. * @summary Get the number of calendar months between the given dates.
  7. *
  8. * @description
  9. * Get the number of calendar months between the given dates.
  10. *
  11. * @param {Date|Number} dateLeft - the later date
  12. * @param {Date|Number} dateRight - the earlier date
  13. * @returns {Number} the number of calendar months
  14. * @throws {TypeError} 2 arguments required
  15. *
  16. * @example
  17. * // How many calendar months are between 31 January 2014 and 1 September 2014?
  18. * const result = differenceInCalendarMonths(
  19. * new Date(2014, 8, 1),
  20. * new Date(2014, 0, 31)
  21. * )
  22. * //=> 8
  23. */
  24. export default function differenceInCalendarMonths(dirtyDateLeft, dirtyDateRight) {
  25. requiredArgs(2, arguments);
  26. var dateLeft = toDate(dirtyDateLeft);
  27. var dateRight = toDate(dirtyDateRight);
  28. var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear();
  29. var monthDiff = dateLeft.getMonth() - dateRight.getMonth();
  30. return yearDiff * 12 + monthDiff;
  31. }