1 | import { getRoundingMethod } from "./_lib/getRoundingMethod.js";
|
2 | import { differenceInDays } from "./differenceInDays.js";
|
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 | * @param laterDate - The later date
|
25 | * @param earlierDate - The earlier date
|
26 | * @param options - An object with options
|
27 | *
|
28 | * @returns The number of full weeks
|
29 | *
|
30 | * @example
|
31 | * // How many full weeks are between 5 July 2014 and 20 July 2014?
|
32 | * const result = differenceInWeeks(new Date(2014, 6, 20), new Date(2014, 6, 5))
|
33 | * //=> 2
|
34 | *
|
35 | * @example
|
36 | * // How many full weeks are between
|
37 | * // 1 March 2020 0:00 and 6 June 2020 0:00 ?
|
38 | * // Note: because local time is used, the
|
39 | * // result will always be 8 weeks (54 days),
|
40 | * // even if DST starts and the period has
|
41 | * // only 54*24-1 hours.
|
42 | * const result = differenceInWeeks(
|
43 | * new Date(2020, 5, 1),
|
44 | * new Date(2020, 2, 6)
|
45 | * )
|
46 | * //=> 8
|
47 | */
|
48 | export function differenceInWeeks(laterDate, earlierDate, options) {
|
49 | const diff = differenceInDays(laterDate, earlierDate, options) / 7;
|
50 | return getRoundingMethod(options?.roundingMethod)(diff);
|
51 | }
|
52 |
|
53 | // Fallback for modularized imports:
|
54 | export default differenceInWeeks;
|