differenceInCalendarWeeks.mjs 2.0 KB

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