UNPKG

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