index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. var parse = require('../parse/index.js')
  2. var differenceInCalendarYears = require('../difference_in_calendar_years/index.js')
  3. var compareAsc = require('../compare_asc/index.js')
  4. /**
  5. * @category Year Helpers
  6. * @summary Get the number of full years between the given dates.
  7. *
  8. * @description
  9. * Get the number of full years 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 years
  14. *
  15. * @example
  16. * // How many full years are between 31 December 2013 and 11 February 2015?
  17. * var result = differenceInYears(
  18. * new Date(2015, 1, 11),
  19. * new Date(2013, 11, 31)
  20. * )
  21. * //=> 1
  22. */
  23. function differenceInYears (dirtyDateLeft, dirtyDateRight) {
  24. var dateLeft = parse(dirtyDateLeft)
  25. var dateRight = parse(dirtyDateRight)
  26. var sign = compareAsc(dateLeft, dateRight)
  27. var difference = Math.abs(differenceInCalendarYears(dateLeft, dateRight))
  28. dateLeft.setFullYear(dateLeft.getFullYear() - sign * difference)
  29. // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full
  30. // If so, result must be decreased by 1 in absolute value
  31. var isLastYearNotFull = compareAsc(dateLeft, dateRight) === -sign
  32. return sign * (difference - isLastYearNotFull)
  33. }
  34. module.exports = differenceInYears