index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. * ### v2.0.0 breaking changes:
  16. *
  17. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  18. *
  19. * @param {Date|Number} dateLeft - the later date
  20. * @param {Date|Number} dateRight - the earlier date
  21. * @returns {Number} the number of calendar ISO weeks
  22. * @throws {TypeError} 2 arguments required
  23. *
  24. * @example
  25. * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014?
  26. * const result = differenceInCalendarISOWeeks(
  27. * new Date(2014, 6, 21),
  28. * new Date(2014, 6, 6)
  29. * )
  30. * //=> 3
  31. */
  32. export default function differenceInCalendarISOWeeks(dirtyDateLeft, dirtyDateRight) {
  33. requiredArgs(2, arguments);
  34. var startOfISOWeekLeft = startOfISOWeek(dirtyDateLeft);
  35. var startOfISOWeekRight = startOfISOWeek(dirtyDateRight);
  36. var timestampLeft = startOfISOWeekLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfISOWeekLeft);
  37. var timestampRight = startOfISOWeekRight.getTime() - getTimezoneOffsetInMilliseconds(startOfISOWeekRight); // Round the number of days to the nearest integer
  38. // because the number of milliseconds in a week is not constant
  39. // (e.g. it's different in the week of the daylight saving time clock shift)
  40. return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK);
  41. }