UNPKG

1.86 kBJavaScriptView Raw
1import { constructFrom } from "./constructFrom.js";
2import { differenceInCalendarDays } from "./differenceInCalendarDays.js";
3import { startOfISOWeekYear } from "./startOfISOWeekYear.js";
4import { toDate } from "./toDate.js";
5
6/**
7 * The {@link setISOWeekYear} function options.
8 */
9
10/**
11 * @name setISOWeekYear
12 * @category ISO Week-Numbering Year Helpers
13 * @summary Set the ISO week-numbering year to the given date.
14 *
15 * @description
16 * Set the ISO week-numbering year to the given date,
17 * saving the week number and the weekday number.
18 *
19 * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
20 *
21 * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).
22 * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
23 *
24 * @param date - The date to be changed
25 * @param weekYear - The ISO week-numbering year of the new date
26 * @param options - An object with options
27 *
28 * @returns The new date with the ISO week-numbering year set
29 *
30 * @example
31 * // Set ISO week-numbering year 2007 to 29 December 2008:
32 * const result = setISOWeekYear(new Date(2008, 11, 29), 2007)
33 * //=> Mon Jan 01 2007 00:00:00
34 */
35export function setISOWeekYear(date, weekYear, options) {
36 let _date = toDate(date, options?.in);
37 const diff = differenceInCalendarDays(
38 _date,
39 startOfISOWeekYear(_date, options),
40 );
41 const fourthOfJanuary = constructFrom(options?.in || date, 0);
42 fourthOfJanuary.setFullYear(weekYear, 0, 4);
43 fourthOfJanuary.setHours(0, 0, 0, 0);
44 _date = startOfISOWeekYear(fourthOfJanuary);
45 _date.setDate(_date.getDate() + diff);
46 return _date;
47}
48
49// Fallback for modularized imports:
50export default setISOWeekYear;