UNPKG

2.61 kBJavaScriptView Raw
1import { getDefaultOptions } from "./_lib/defaultOptions.js";
2import { constructFrom } from "./constructFrom.js";
3import { startOfWeek } from "./startOfWeek.js";
4import { toDate } from "./toDate.js";
5
6/**
7 * The {@link getWeekYear} function options.
8 */
9
10/**
11 * @name getWeekYear
12 * @category Week-Numbering Year Helpers
13 * @summary Get the local week-numbering year of the given date.
14 *
15 * @description
16 * Get the local week-numbering year 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 local week-numbering year
28 *
29 * @example
30 * // Which week numbering year is 26 December 2004 with the default settings?
31 * const result = getWeekYear(new Date(2004, 11, 26))
32 * //=> 2005
33 *
34 * @example
35 * // Which week numbering year is 26 December 2004 if week starts on Saturday?
36 * const result = getWeekYear(new Date(2004, 11, 26), { weekStartsOn: 6 })
37 * //=> 2004
38 *
39 * @example
40 * // Which week numbering year is 26 December 2004 if the first week contains 4 January?
41 * const result = getWeekYear(new Date(2004, 11, 26), { firstWeekContainsDate: 4 })
42 * //=> 2004
43 */
44export function getWeekYear(date, options) {
45 const _date = toDate(date, options?.in);
46 const year = _date.getFullYear();
47
48 const defaultOptions = getDefaultOptions();
49 const firstWeekContainsDate =
50 options?.firstWeekContainsDate ??
51 options?.locale?.options?.firstWeekContainsDate ??
52 defaultOptions.firstWeekContainsDate ??
53 defaultOptions.locale?.options?.firstWeekContainsDate ??
54 1;
55
56 const firstWeekOfNextYear = constructFrom(options?.in || date, 0);
57 firstWeekOfNextYear.setFullYear(year + 1, 0, firstWeekContainsDate);
58 firstWeekOfNextYear.setHours(0, 0, 0, 0);
59 const startOfNextYear = startOfWeek(firstWeekOfNextYear, options);
60
61 const firstWeekOfThisYear = constructFrom(options?.in || date, 0);
62 firstWeekOfThisYear.setFullYear(year, 0, firstWeekContainsDate);
63 firstWeekOfThisYear.setHours(0, 0, 0, 0);
64 const startOfThisYear = startOfWeek(firstWeekOfThisYear, options);
65
66 if (+_date >= +startOfNextYear) {
67 return year + 1;
68 } else if (+_date >= +startOfThisYear) {
69 return year;
70 } else {
71 return year - 1;
72 }
73}
74
75// Fallback for modularized imports:
76export default getWeekYear;