differenceInCalendarISOWeeks.mjs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { millisecondsInWeek } from "./constants.mjs";
  2. import { startOfISOWeek } from "./startOfISOWeek.mjs";
  3. import { getTimezoneOffsetInMilliseconds } from "./_lib/getTimezoneOffsetInMilliseconds.mjs";
  4. /**
  5. * @name differenceInCalendarISOWeeks
  6. * @category ISO Week Helpers
  7. * @summary Get the number of calendar ISO weeks between the given dates.
  8. *
  9. * @description
  10. * Get the number of calendar ISO weeks between the given dates.
  11. *
  12. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  13. *
  14. * @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).
  15. *
  16. * @param dateLeft - The later date
  17. * @param dateRight - The earlier date
  18. *
  19. * @returns The number of calendar ISO weeks
  20. *
  21. * @example
  22. * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014?
  23. * const result = differenceInCalendarISOWeeks(
  24. * new Date(2014, 6, 21),
  25. * new Date(2014, 6, 6)
  26. * )
  27. * //=> 3
  28. */
  29. export function differenceInCalendarISOWeeks(dateLeft, dateRight) {
  30. const startOfISOWeekLeft = startOfISOWeek(dateLeft);
  31. const startOfISOWeekRight = startOfISOWeek(dateRight);
  32. const timestampLeft =
  33. +startOfISOWeekLeft - getTimezoneOffsetInMilliseconds(startOfISOWeekLeft);
  34. const timestampRight =
  35. +startOfISOWeekRight - getTimezoneOffsetInMilliseconds(startOfISOWeekRight);
  36. // Round the number of weeks to the nearest integer because the number of
  37. // milliseconds in a week is not constant (e.g. it's different in the week of
  38. // the daylight saving time clock shift).
  39. return Math.round((timestampLeft - timestampRight) / millisecondsInWeek);
  40. }
  41. // Fallback for modularized imports:
  42. export default differenceInCalendarISOWeeks;