index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import getTimezoneOffsetInMilliseconds from "../_lib/getTimezoneOffsetInMilliseconds/index.js";
  2. import startOfISOWeek from "../startOfISOWeek/index.js";
  3. import requiredArgs from "../_lib/requiredArgs/index.js";
  4. var MILLISECONDS_IN_WEEK = 604800000;
  5. /**
  6. * @name differenceInCalendarISOWeeks
  7. * @category ISO Week Helpers
  8. * @summary Get the number of calendar ISO weeks between the given dates.
  9. *
  10. * @description
  11. * Get the number of calendar ISO weeks between the given dates.
  12. *
  13. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  14. *
  15. * @param {Date|Number} dateLeft - the later date
  16. * @param {Date|Number} dateRight - the earlier date
  17. * @returns {Number} the number of calendar ISO weeks
  18. * @throws {TypeError} 2 arguments required
  19. *
  20. * @example
  21. * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014?
  22. * const result = differenceInCalendarISOWeeks(
  23. * new Date(2014, 6, 21),
  24. * new Date(2014, 6, 6)
  25. * )
  26. * //=> 3
  27. */
  28. export default function differenceInCalendarISOWeeks(dirtyDateLeft, dirtyDateRight) {
  29. requiredArgs(2, arguments);
  30. var startOfISOWeekLeft = startOfISOWeek(dirtyDateLeft);
  31. var startOfISOWeekRight = startOfISOWeek(dirtyDateRight);
  32. var timestampLeft = startOfISOWeekLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfISOWeekLeft);
  33. var timestampRight = startOfISOWeekRight.getTime() - getTimezoneOffsetInMilliseconds(startOfISOWeekRight);
  34. // Round the number of days to the nearest integer
  35. // because the number of milliseconds in a week is not constant
  36. // (e.g. it's different in the week of the daylight saving time clock shift)
  37. return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK);
  38. }