differenceInCalendarISOWeeks.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { getTimezoneOffsetInMilliseconds } from "./_lib/getTimezoneOffsetInMilliseconds.js";
  2. import { normalizeDates } from "./_lib/normalizeDates.js";
  3. import { millisecondsInWeek } from "./constants.js";
  4. import { startOfISOWeek } from "./startOfISOWeek.js";
  5. /**
  6. * The {@link differenceInCalendarISOWeeks} function options.
  7. */
  8. /**
  9. * @name differenceInCalendarISOWeeks
  10. * @category ISO Week Helpers
  11. * @summary Get the number of calendar ISO weeks between the given dates.
  12. *
  13. * @description
  14. * Get the number of calendar ISO weeks between the given dates.
  15. *
  16. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  17. *
  18. * @param laterDate - The later date
  19. * @param earlierDate - The earlier date
  20. * @param options - An object with options
  21. *
  22. * @returns The number of calendar ISO weeks
  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 function differenceInCalendarISOWeeks(laterDate, earlierDate, options) {
  33. const [laterDate_, earlierDate_] = normalizeDates(
  34. options?.in,
  35. laterDate,
  36. earlierDate,
  37. );
  38. const startOfISOWeekLeft = startOfISOWeek(laterDate_);
  39. const startOfISOWeekRight = startOfISOWeek(earlierDate_);
  40. const timestampLeft =
  41. +startOfISOWeekLeft - getTimezoneOffsetInMilliseconds(startOfISOWeekLeft);
  42. const timestampRight =
  43. +startOfISOWeekRight - getTimezoneOffsetInMilliseconds(startOfISOWeekRight);
  44. // Round the number of weeks to the nearest integer because the number of
  45. // milliseconds in a week is not constant (e.g. it's different in the week of
  46. // the daylight saving time clock shift).
  47. return Math.round((timestampLeft - timestampRight) / millisecondsInWeek);
  48. }
  49. // Fallback for modularized imports:
  50. export default differenceInCalendarISOWeeks;