index.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var parse = require('../parse/index.js')
  2. var differenceInCalendarISOYears = require('../difference_in_calendar_iso_years/index.js')
  3. var compareAsc = require('../compare_asc/index.js')
  4. var subISOYears = require('../sub_iso_years/index.js')
  5. /**
  6. * @category ISO Week-Numbering Year Helpers
  7. * @summary Get the number of full ISO week-numbering years between the given dates.
  8. *
  9. * @description
  10. * Get the number of full ISO week-numbering years between the given dates.
  11. *
  12. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  13. *
  14. * @param {Date|String|Number} dateLeft - the later date
  15. * @param {Date|String|Number} dateRight - the earlier date
  16. * @returns {Number} the number of full ISO week-numbering years
  17. *
  18. * @example
  19. * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012?
  20. * var result = differenceInISOYears(
  21. * new Date(2012, 0, 1),
  22. * new Date(2010, 0, 1)
  23. * )
  24. * //=> 1
  25. */
  26. function differenceInISOYears (dirtyDateLeft, dirtyDateRight) {
  27. var dateLeft = parse(dirtyDateLeft)
  28. var dateRight = parse(dirtyDateRight)
  29. var sign = compareAsc(dateLeft, dateRight)
  30. var difference = Math.abs(differenceInCalendarISOYears(dateLeft, dateRight))
  31. dateLeft = subISOYears(dateLeft, sign * difference)
  32. // Math.abs(diff in full ISO years - diff in calendar ISO years) === 1
  33. // if last calendar ISO year is not full
  34. // If so, result must be decreased by 1 in absolute value
  35. var isLastISOYearNotFull = compareAsc(dateLeft, dateRight) === -sign
  36. return sign * (difference - isLastISOYearNotFull)
  37. }
  38. module.exports = differenceInISOYears