getWeekOfMonth.js 1.6 KB

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