differenceInCalendarWeeks.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. exports.differenceInCalendarWeeks = differenceInCalendarWeeks;
  3. var _index = require("./constants.js");
  4. var _index2 = require("./startOfWeek.js");
  5. var _index3 = require("./_lib/getTimezoneOffsetInMilliseconds.js");
  6. /**
  7. * The {@link differenceInCalendarWeeks} function options.
  8. */
  9. /**
  10. * @name differenceInCalendarWeeks
  11. * @category Week Helpers
  12. * @summary Get the number of calendar weeks between the given dates.
  13. *
  14. * @description
  15. * Get the number of calendar weeks between the given dates.
  16. *
  17. * @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).
  18. *
  19. * @param dateLeft - The later date
  20. * @param dateRight - The earlier date
  21. * @param options - An object with options.
  22. *
  23. * @returns The number of calendar weeks
  24. *
  25. * @example
  26. * // How many calendar weeks are between 5 July 2014 and 20 July 2014?
  27. * const result = differenceInCalendarWeeks(
  28. * new Date(2014, 6, 20),
  29. * new Date(2014, 6, 5)
  30. * )
  31. * //=> 3
  32. *
  33. * @example
  34. * // If the week starts on Monday,
  35. * // how many calendar weeks are between 5 July 2014 and 20 July 2014?
  36. * const result = differenceInCalendarWeeks(
  37. * new Date(2014, 6, 20),
  38. * new Date(2014, 6, 5),
  39. * { weekStartsOn: 1 }
  40. * )
  41. * //=> 2
  42. */
  43. function differenceInCalendarWeeks(dateLeft, dateRight, options) {
  44. const startOfWeekLeft = (0, _index2.startOfWeek)(dateLeft, options);
  45. const startOfWeekRight = (0, _index2.startOfWeek)(dateRight, options);
  46. const timestampLeft =
  47. +startOfWeekLeft -
  48. (0, _index3.getTimezoneOffsetInMilliseconds)(startOfWeekLeft);
  49. const timestampRight =
  50. +startOfWeekRight -
  51. (0, _index3.getTimezoneOffsetInMilliseconds)(startOfWeekRight);
  52. // Round the number of days to the nearest integer because the number of
  53. // milliseconds in a days is not constant (e.g. it's different in the week of
  54. // the daylight saving time clock shift).
  55. return Math.round(
  56. (timestampLeft - timestampRight) / _index.millisecondsInWeek,
  57. );
  58. }