UNPKG

1.61 kBJavaScriptView Raw
1"use strict";
2exports.getWeekOfMonth = getWeekOfMonth;
3var _index = require("./getDate.js");
4var _index2 = require("./getDay.js");
5var _index3 = require("./startOfMonth.js");
6
7var _index4 = require("./_lib/defaultOptions.js");
8
9/**
10 * The {@link getWeekOfMonth} function options.
11 */
12
13/**
14 * @name getWeekOfMonth
15 * @category Week Helpers
16 * @summary Get the week of the month of the given date.
17 *
18 * @description
19 * Get the week of the month of the given date.
20 *
21 * @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).
22 *
23 * @param date - The given date
24 * @param options - An object with options.
25 *
26 * @returns The week of month
27 *
28 * @example
29 * // Which week of the month is 9 November 2017?
30 * const result = getWeekOfMonth(new Date(2017, 10, 9))
31 * //=> 2
32 */
33function getWeekOfMonth(date, options) {
34 const defaultOptions = (0, _index4.getDefaultOptions)();
35 const weekStartsOn =
36 options?.weekStartsOn ??
37 options?.locale?.options?.weekStartsOn ??
38 defaultOptions.weekStartsOn ??
39 defaultOptions.locale?.options?.weekStartsOn ??
40 0;
41
42 const currentDayOfMonth = (0, _index.getDate)(date);
43 if (isNaN(currentDayOfMonth)) return NaN;
44
45 const startWeekDay = (0, _index2.getDay)((0, _index3.startOfMonth)(date));
46
47 let lastDayOfFirstWeek = weekStartsOn - startWeekDay;
48 if (lastDayOfFirstWeek <= 0) lastDayOfFirstWeek += 7;
49
50 const remainingDaysAfterFirstWeek = currentDayOfMonth - lastDayOfFirstWeek;
51 return Math.ceil(remainingDaysAfterFirstWeek / 7) + 1;
52}