UNPKG

1.67 kBJavaScriptView Raw
1import { toDate } from "./toDate.mjs";
2import { getDefaultOptions } from "./_lib/defaultOptions.mjs";
3
4/**
5 * The {@link lastDayOfWeek} function options.
6 */
7
8/**
9 * @name lastDayOfWeek
10 * @category Week Helpers
11 * @summary Return the last day of a week for the given date.
12 *
13 * @description
14 * Return the last day of a week for the given date.
15 * The result will be in the local timezone.
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 *
19 * @param date - The original date
20 * @param options - An object with options
21 *
22 * @returns The last day of a week
23 *
24 * @example
25 * // The last day of a week for 2 September 2014 11:55:00:
26 * const result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0))
27 * //=> Sat Sep 06 2014 00:00:00
28 *
29 * @example
30 * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00:
31 * const result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
32 * //=> Sun Sep 07 2014 00:00:00
33 */
34export function lastDayOfWeek(date, options) {
35 const defaultOptions = getDefaultOptions();
36 const weekStartsOn =
37 options?.weekStartsOn ??
38 options?.locale?.options?.weekStartsOn ??
39 defaultOptions.weekStartsOn ??
40 defaultOptions.locale?.options?.weekStartsOn ??
41 0;
42
43 const _date = toDate(date);
44 const day = _date.getDay();
45 const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
46
47 _date.setHours(0, 0, 0, 0);
48 _date.setDate(_date.getDate() + diff);
49 return _date;
50}
51
52// Fallback for modularized imports:
53export default lastDayOfWeek;