1 | import { millisecondsInWeek } from "./constants.js";
|
2 | import { startOfWeek } from "./startOfWeek.js";
|
3 | import { startOfWeekYear } from "./startOfWeekYear.js";
|
4 | import { toDate } from "./toDate.js";
|
5 |
|
6 | /**
|
7 | * The {@link getWeek} function options.
|
8 | */
|
9 |
|
10 | /**
|
11 | * @name getWeek
|
12 | * @category Week Helpers
|
13 | * @summary Get the local week index of the given date.
|
14 | *
|
15 | * @description
|
16 | * Get the local week index of the given date.
|
17 | * The exact calculation depends on the values of
|
18 | * `options.weekStartsOn` (which is the index of the first day of the week)
|
19 | * and `options.firstWeekContainsDate` (which is the day of January, which is always in
|
20 | * the first week of the week-numbering year)
|
21 | *
|
22 | * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
|
23 | *
|
24 | * @param date - The given date
|
25 | * @param options - An object with options
|
26 | *
|
27 | * @returns The week
|
28 | *
|
29 | * @example
|
30 | * // Which week of the local week numbering year is 2 January 2005 with default options?
|
31 | * const result = getWeek(new Date(2005, 0, 2))
|
32 | * //=> 2
|
33 | *
|
34 | * @example
|
35 | * // Which week of the local week numbering year is 2 January 2005,
|
36 | * // if Monday is the first day of the week,
|
37 | * // and the first week of the year always contains 4 January?
|
38 | * const result = getWeek(new Date(2005, 0, 2), {
|
39 | * weekStartsOn: 1,
|
40 | * firstWeekContainsDate: 4
|
41 | * })
|
42 | * //=> 53
|
43 | */
|
44 | export function getWeek(date, options) {
|
45 | const _date = toDate(date, options?.in);
|
46 | const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options);
|
47 |
|
48 | // Round the number of weeks to the nearest integer because the number of
|
49 | // milliseconds in a week is not constant (e.g. it's different in the week of
|
50 | // the daylight saving time clock shift).
|
51 | return Math.round(diff / millisecondsInWeek) + 1;
|
52 | }
|
53 |
|
54 | // Fallback for modularized imports:
|
55 | export default getWeek;
|