index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import startOfWeek from "../startOfWeek/index.js";
  2. import getTimezoneOffsetInMilliseconds from "../_lib/getTimezoneOffsetInMilliseconds/index.js";
  3. import requiredArgs from "../_lib/requiredArgs/index.js";
  4. var MILLISECONDS_IN_WEEK = 604800000;
  5. /**
  6. * @name differenceInCalendarWeeks
  7. * @category Week Helpers
  8. * @summary Get the number of calendar weeks between the given dates.
  9. *
  10. * @description
  11. * Get the number of calendar weeks between the given dates.
  12. *
  13. * ### v2.0.0 breaking changes:
  14. *
  15. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  16. *
  17. * @param {Date|Number} dateLeft - the later date
  18. * @param {Date|Number} dateRight - the earlier date
  19. * @param {Object} [options] - an object with options.
  20. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  21. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  22. * @returns {Number} the number of calendar weeks
  23. * @throws {TypeError} 2 arguments required
  24. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  25. *
  26. * @example
  27. * // How many calendar weeks are between 5 July 2014 and 20 July 2014?
  28. * const result = differenceInCalendarWeeks(
  29. * new Date(2014, 6, 20),
  30. * new Date(2014, 6, 5)
  31. * )
  32. * //=> 3
  33. *
  34. * @example
  35. * // If the week starts on Monday,
  36. * // how many calendar weeks are between 5 July 2014 and 20 July 2014?
  37. * const result = differenceInCalendarWeeks(
  38. * new Date(2014, 6, 20),
  39. * new Date(2014, 6, 5),
  40. * { weekStartsOn: 1 }
  41. * )
  42. * //=> 2
  43. */
  44. export default function differenceInCalendarWeeks(dirtyDateLeft, dirtyDateRight, dirtyOptions) {
  45. requiredArgs(2, arguments);
  46. var startOfWeekLeft = startOfWeek(dirtyDateLeft, dirtyOptions);
  47. var startOfWeekRight = startOfWeek(dirtyDateRight, dirtyOptions);
  48. var timestampLeft = startOfWeekLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfWeekLeft);
  49. var timestampRight = startOfWeekRight.getTime() - getTimezoneOffsetInMilliseconds(startOfWeekRight); // Round the number of days to the nearest integer
  50. // because the number of milliseconds in a week is not constant
  51. // (e.g. it's different in the week of the daylight saving time clock shift)
  52. return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK);
  53. }