getWeeksInMonth.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { differenceInCalendarWeeks } from "./differenceInCalendarWeeks.js";
  2. import { lastDayOfMonth } from "./lastDayOfMonth.js";
  3. import { startOfMonth } from "./startOfMonth.js";
  4. import { toDate } from "./toDate.js";
  5. /**
  6. * The {@link getWeeksInMonth} function options.
  7. */
  8. /**
  9. * @name getWeeksInMonth
  10. * @category Week Helpers
  11. * @summary Get the number of calendar weeks a month spans.
  12. *
  13. * @description
  14. * Get the number of calendar weeks the month in the given date spans.
  15. *
  16. * @param date - The given date
  17. * @param options - An object with options.
  18. *
  19. * @returns The number of calendar weeks
  20. *
  21. * @example
  22. * // How many calendar weeks does February 2015 span?
  23. * const result = getWeeksInMonth(new Date(2015, 1, 8))
  24. * //=> 4
  25. *
  26. * @example
  27. * // If the week starts on Monday,
  28. * // how many calendar weeks does July 2017 span?
  29. * const result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })
  30. * //=> 6
  31. */
  32. export function getWeeksInMonth(date, options) {
  33. const contextDate = toDate(date, options?.in);
  34. return (
  35. differenceInCalendarWeeks(
  36. lastDayOfMonth(contextDate, options),
  37. startOfMonth(contextDate, options),
  38. options,
  39. ) + 1
  40. );
  41. }
  42. // Fallback for modularized imports:
  43. export default getWeeksInMonth;