index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import toDate from "../toDate/index.js";
  2. import differenceInCalendarISOWeekYears from "../differenceInCalendarISOWeekYears/index.js";
  3. import compareAsc from "../compareAsc/index.js";
  4. import subISOWeekYears from "../subISOWeekYears/index.js";
  5. import requiredArgs from "../_lib/requiredArgs/index.js";
  6. /**
  7. * @name differenceInISOWeekYears
  8. * @category ISO Week-Numbering Year Helpers
  9. * @summary Get the number of full ISO week-numbering years between the given dates.
  10. *
  11. * @description
  12. * Get the number of full ISO week-numbering years between the given dates.
  13. *
  14. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  15. *
  16. * ### v2.0.0 breaking changes:
  17. *
  18. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  19. *
  20. * - The function was renamed from `differenceInISOYears` to `differenceInISOWeekYears`.
  21. * "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
  22. * This change makes the name consistent with
  23. * locale-dependent week-numbering year helpers, e.g., `addWeekYears`.
  24. *
  25. * @param {Date|Number} dateLeft - the later date
  26. * @param {Date|Number} dateRight - the earlier date
  27. * @returns {Number} the number of full ISO week-numbering years
  28. * @throws {TypeError} 2 arguments required
  29. *
  30. * @example
  31. * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012?
  32. * var result = differenceInISOWeekYears(
  33. * new Date(2012, 0, 1),
  34. * new Date(2010, 0, 1)
  35. * )
  36. * //=> 1
  37. */
  38. export default function differenceInISOWeekYears(dirtyDateLeft, dirtyDateRight) {
  39. requiredArgs(2, arguments);
  40. var dateLeft = toDate(dirtyDateLeft);
  41. var dateRight = toDate(dirtyDateRight);
  42. var sign = compareAsc(dateLeft, dateRight);
  43. var difference = Math.abs(differenceInCalendarISOWeekYears(dateLeft, dateRight));
  44. dateLeft = subISOWeekYears(dateLeft, sign * difference); // Math.abs(diff in full ISO years - diff in calendar ISO years) === 1
  45. // if last calendar ISO year is not full
  46. // If so, result must be decreased by 1 in absolute value
  47. var isLastISOWeekYearNotFull = Number(compareAsc(dateLeft, dateRight) === -sign);
  48. var result = sign * (difference - isLastISOWeekYearNotFull); // Prevent negative zero
  49. return result === 0 ? 0 : result;
  50. }