index.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. * @param {Date|Number} dateLeft - the later date
  14. * @param {Date|Number} dateRight - the earlier date
  15. * @param {Object} [options] - an object with options.
  16. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  17. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  18. * @returns {Number} the number of calendar weeks
  19. * @throws {TypeError} 2 arguments required
  20. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  21. *
  22. * @example
  23. * // How many calendar weeks are between 5 July 2014 and 20 July 2014?
  24. * const result = differenceInCalendarWeeks(
  25. * new Date(2014, 6, 20),
  26. * new Date(2014, 6, 5)
  27. * )
  28. * //=> 3
  29. *
  30. * @example
  31. * // If the week starts on Monday,
  32. * // how many calendar weeks are between 5 July 2014 and 20 July 2014?
  33. * const result = differenceInCalendarWeeks(
  34. * new Date(2014, 6, 20),
  35. * new Date(2014, 6, 5),
  36. * { weekStartsOn: 1 }
  37. * )
  38. * //=> 2
  39. */
  40. export default function differenceInCalendarWeeks(dirtyDateLeft, dirtyDateRight, options) {
  41. requiredArgs(2, arguments);
  42. var startOfWeekLeft = startOfWeek(dirtyDateLeft, options);
  43. var startOfWeekRight = startOfWeek(dirtyDateRight, options);
  44. var timestampLeft = startOfWeekLeft.getTime() - getTimezoneOffsetInMilliseconds(startOfWeekLeft);
  45. var timestampRight = startOfWeekRight.getTime() - getTimezoneOffsetInMilliseconds(startOfWeekRight);
  46. // Round the number of days to the nearest integer
  47. // because the number of milliseconds in a week is not constant
  48. // (e.g. it's different in the week of the daylight saving time clock shift)
  49. return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK);
  50. }