getWeekOfMonth.mjs 1.6 KB

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