index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import differenceInCalendarWeeks from "../differenceInCalendarWeeks/index.js";
  2. import lastDayOfMonth from "../lastDayOfMonth/index.js";
  3. import startOfMonth from "../startOfMonth/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. /**
  6. * @name getWeeksInMonth
  7. * @category Week Helpers
  8. * @summary Get the number of calendar weeks a month spans.
  9. *
  10. * @description
  11. * Get the number of calendar weeks the month in the given date spans.
  12. *
  13. * ### v2.0.0 breaking changes:
  14. *
  15. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  16. *
  17. * @param {Date|Number} date - the given date
  18. * @param {Object} [options] - an object with options.
  19. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  20. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  21. * @returns {Number} the number of calendar weeks
  22. * @throws {TypeError} 2 arguments required
  23. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  24. *
  25. * @example
  26. * // How many calendar weeks does February 2015 span?
  27. * const result = getWeeksInMonth(new Date(2015, 1, 8))
  28. * //=> 4
  29. *
  30. * @example
  31. * // If the week starts on Monday,
  32. * // how many calendar weeks does July 2017 span?
  33. * const result = getWeeksInMonth(new Date(2017, 6, 5), { weekStartsOn: 1 })
  34. * //=> 6
  35. */
  36. export default function getWeeksInMonth(date, options) {
  37. requiredArgs(1, arguments);
  38. return differenceInCalendarWeeks(lastDayOfMonth(date), startOfMonth(date), options) + 1;
  39. }