UNPKG

1.85 kBJavaScriptView Raw
1import { getTimezoneOffsetInMilliseconds } from "./_lib/getTimezoneOffsetInMilliseconds.js";
2import { normalizeDates } from "./_lib/normalizeDates.js";
3import { millisecondsInWeek } from "./constants.js";
4import { startOfWeek } from "./startOfWeek.js";
5
6/**
7 * The {@link differenceInCalendarWeeks} function options.
8 */
9
10/**
11 * @name differenceInCalendarWeeks
12 * @category Week Helpers
13 * @summary Get the number of calendar weeks between the given dates.
14 *
15 * @description
16 * Get the number of calendar weeks between the given dates.
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 weeks
23 *
24 * @example
25 * // How many calendar weeks are between 5 July 2014 and 20 July 2014?
26 * const result = differenceInCalendarWeeks(
27 * new Date(2014, 6, 20),
28 * new Date(2014, 6, 5)
29 * )
30 * //=> 3
31 *
32 * @example
33 * // If the week starts on Monday,
34 * // how many calendar weeks are between 5 July 2014 and 20 July 2014?
35 * const result = differenceInCalendarWeeks(
36 * new Date(2014, 6, 20),
37 * new Date(2014, 6, 5),
38 * { weekStartsOn: 1 }
39 * )
40 * //=> 2
41 */
42export function differenceInCalendarWeeks(laterDate, earlierDate, options) {
43 const [laterDate_, earlierDate_] = normalizeDates(
44 options?.in,
45 laterDate,
46 earlierDate,
47 );
48
49 const laterStartOfWeek = startOfWeek(laterDate_, options);
50 const earlierStartOfWeek = startOfWeek(earlierDate_, options);
51
52 const laterTimestamp =
53 +laterStartOfWeek - getTimezoneOffsetInMilliseconds(laterStartOfWeek);
54 const earlierTimestamp =
55 +earlierStartOfWeek - getTimezoneOffsetInMilliseconds(earlierStartOfWeek);
56
57 return Math.round((laterTimestamp - earlierTimestamp) / millisecondsInWeek);
58}
59
60// Fallback for modularized imports:
61export default differenceInCalendarWeeks;