index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. var parse = require('../parse/index.js')
  2. var differenceInCalendarMonths = require('../difference_in_calendar_months/index.js')
  3. var compareAsc = require('../compare_asc/index.js')
  4. /**
  5. * @category Month Helpers
  6. * @summary Get the number of full months between the given dates.
  7. *
  8. * @description
  9. * Get the number of full months between the given dates.
  10. *
  11. * @param {Date|String|Number} dateLeft - the later date
  12. * @param {Date|String|Number} dateRight - the earlier date
  13. * @returns {Number} the number of full months
  14. *
  15. * @example
  16. * // How many full months are between 31 January 2014 and 1 September 2014?
  17. * var result = differenceInMonths(
  18. * new Date(2014, 8, 1),
  19. * new Date(2014, 0, 31)
  20. * )
  21. * //=> 7
  22. */
  23. function differenceInMonths (dirtyDateLeft, dirtyDateRight) {
  24. var dateLeft = parse(dirtyDateLeft)
  25. var dateRight = parse(dirtyDateRight)
  26. var sign = compareAsc(dateLeft, dateRight)
  27. var difference = Math.abs(differenceInCalendarMonths(dateLeft, dateRight))
  28. dateLeft.setMonth(dateLeft.getMonth() - sign * difference)
  29. // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full
  30. // If so, result must be decreased by 1 in absolute value
  31. var isLastMonthNotFull = compareAsc(dateLeft, dateRight) === -sign
  32. return sign * (difference - isLastMonthNotFull)
  33. }
  34. module.exports = differenceInMonths