UNPKG

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