getWeekOfMonth.js 1.5 KB

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