UNPKG

1.97 kBJavaScriptView Raw
1import { getRoundingMethod } from "./_lib/getRoundingMethod.mjs";
2import { differenceInDays } from "./differenceInDays.mjs";
3
4/**
5 * The {@link differenceInWeeks} function options.
6 */
7
8/**
9 * @name differenceInWeeks
10 * @category Week Helpers
11 * @summary Get the number of full weeks between the given dates.
12 *
13 * @description
14 * Get the number of full weeks between two dates. Fractional weeks are
15 * truncated towards zero by default.
16 *
17 * One "full week" is the distance between a local time in one day to the same
18 * local time 7 days earlier or later. A full week can sometimes be less than
19 * or more than 7*24 hours if a daylight savings change happens between two dates.
20 *
21 * To ignore DST and only measure exact 7*24-hour periods, use this instead:
22 * `Math.trunc(differenceInHours(dateLeft, dateRight)/(7*24))|0`.
23 *
24 * @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).
25 *
26 * @param dateLeft - The later date
27 * @param dateRight - The earlier date
28 * @param options - An object with options
29 *
30 * @returns The number of full weeks
31 *
32 * @example
33 * // How many full weeks are between 5 July 2014 and 20 July 2014?
34 * const result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))
35 * //=> 2
36 *
37 * @example
38 * // How many full weeks are between
39 * // 1 March 2020 0:00 and 6 June 2020 0:00 ?
40 * // Note: because local time is used, the
41 * // result will always be 8 weeks (54 days),
42 * // even if DST starts and the period has
43 * // only 54*24-1 hours.
44 * const result = differenceInWeeks(
45 * new Date(2020, 5, 1),
46 * new Date(2020, 2, 6)
47 * )
48 * //=> 8
49 */
50export function differenceInWeeks(dateLeft, dateRight, options) {
51 const diff = differenceInDays(dateLeft, dateRight) / 7;
52 return getRoundingMethod(options?.roundingMethod)(diff);
53}
54
55// Fallback for modularized imports:
56export default differenceInWeeks;