getWeeksInMonth.mjs 1.3 KB

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