1 | import { getDefaultOptions } from "./_lib/defaultOptions.js";
|
2 | import { addDays } from "./addDays.js";
|
3 | import { toDate } from "./toDate.js";
|
4 |
|
5 | /**
|
6 | * The {@link setDay} function options.
|
7 | */
|
8 |
|
9 | /**
|
10 | * @name setDay
|
11 | * @category Weekday Helpers
|
12 | * @summary Set the day of the week to the given date.
|
13 | *
|
14 | * @description
|
15 | * Set the day of the week to the given date.
|
16 | *
|
17 | * @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).
|
18 | * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
|
19 | *
|
20 | * @param date - The date to be changed
|
21 | * @param day - The day of the week of the new date
|
22 | * @param options - An object with options.
|
23 | *
|
24 | * @returns The new date with the day of the week set
|
25 | *
|
26 | * @example
|
27 | * // Set week day to Sunday, with the default weekStartsOn of Sunday:
|
28 | * const result = setDay(new Date(2014, 8, 1), 0)
|
29 | * //=> Sun Aug 31 2014 00:00:00
|
30 | *
|
31 | * @example
|
32 | * // Set week day to Sunday, with a weekStartsOn of Monday:
|
33 | * const result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 })
|
34 | * //=> Sun Sep 07 2014 00:00:00
|
35 | */
|
36 | export function setDay(date, day, options) {
|
37 | const defaultOptions = getDefaultOptions();
|
38 | const weekStartsOn =
|
39 | options?.weekStartsOn ??
|
40 | options?.locale?.options?.weekStartsOn ??
|
41 | defaultOptions.weekStartsOn ??
|
42 | defaultOptions.locale?.options?.weekStartsOn ??
|
43 | 0;
|
44 |
|
45 | const date_ = toDate(date, options?.in);
|
46 | const currentDay = date_.getDay();
|
47 |
|
48 | const remainder = day % 7;
|
49 | const dayIndex = (remainder + 7) % 7;
|
50 |
|
51 | const delta = 7 - weekStartsOn;
|
52 | const diff =
|
53 | day < 0 || day > 6
|
54 | ? day - ((currentDay + delta) % 7)
|
55 | : ((dayIndex + delta) % 7) - ((currentDay + delta) % 7);
|
56 | return addDays(date_, diff, options);
|
57 | }
|
58 |
|
59 | // Fallback for modularized imports:
|
60 | export default setDay;
|