index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  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. * @param {Date|Number} date - the given date
  14. * @param {Object} [options] - an object with options.
  15. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  16. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  17. * @returns {Number} the number of calendar weeks
  18. * @throws {TypeError} 2 arguments required
  19. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  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 default function getWeeksInMonth(date, options) {
  33. requiredArgs(1, arguments);
  34. return differenceInCalendarWeeks(lastDayOfMonth(date), startOfMonth(date), options) + 1;
  35. }