differenceInISOWeekYears.mjs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { compareAsc } from "./compareAsc.mjs";
  2. import { differenceInCalendarISOWeekYears } from "./differenceInCalendarISOWeekYears.mjs";
  3. import { subISOWeekYears } from "./subISOWeekYears.mjs";
  4. import { toDate } from "./toDate.mjs";
  5. /**
  6. * @name differenceInISOWeekYears
  7. * @category ISO Week-Numbering Year Helpers
  8. * @summary Get the number of full ISO week-numbering years between the given dates.
  9. *
  10. * @description
  11. * Get the number of full ISO week-numbering years between the given dates.
  12. *
  13. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  14. *
  15. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  16. *
  17. * @param dateLeft - The later date
  18. * @param dateRight - The earlier date
  19. *
  20. * @returns The number of full ISO week-numbering years
  21. *
  22. * @example
  23. * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012?
  24. * const result = differenceInISOWeekYears(
  25. * new Date(2012, 0, 1),
  26. * new Date(2010, 0, 1)
  27. * )
  28. * //=> 1
  29. */
  30. export function differenceInISOWeekYears(dateLeft, dateRight) {
  31. let _dateLeft = toDate(dateLeft);
  32. const _dateRight = toDate(dateRight);
  33. const sign = compareAsc(_dateLeft, _dateRight);
  34. const difference = Math.abs(
  35. differenceInCalendarISOWeekYears(_dateLeft, _dateRight),
  36. );
  37. _dateLeft = subISOWeekYears(_dateLeft, sign * difference);
  38. // Math.abs(diff in full ISO years - diff in calendar ISO years) === 1
  39. // if last calendar ISO year is not full
  40. // If so, result must be decreased by 1 in absolute value
  41. const isLastISOWeekYearNotFull = Number(
  42. compareAsc(_dateLeft, _dateRight) === -sign,
  43. );
  44. const result = sign * (difference - isLastISOWeekYearNotFull);
  45. // Prevent negative zero
  46. return result === 0 ? 0 : result;
  47. }
  48. // Fallback for modularized imports:
  49. export default differenceInISOWeekYears;