index.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import getDate from "../getDate/index.js";
  2. import getDay from "../getDay/index.js";
  3. import startOfMonth from "../startOfMonth/index.js";
  4. import toInteger from "../_lib/toInteger/index.js";
  5. import requiredArgs from "../_lib/requiredArgs/index.js";
  6. /**
  7. * @name getWeekOfMonth
  8. * @category Week Helpers
  9. * @summary Get the week of the month of the given date.
  10. *
  11. * @description
  12. * Get the week of the month of the given date.
  13. *
  14. * ### v2.0.0 breaking changes:
  15. *
  16. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  17. *
  18. * @param {Date|Number} date - the given date
  19. * @param {Object} [options] - an object with options.
  20. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  21. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  22. * @returns {Number} the week of month
  23. * @throws {TypeError} 1 argument required
  24. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  25. *
  26. * @example
  27. * // Which week of the month is 9 November 2017?
  28. * var result = getWeekOfMonth(new Date(2017, 10, 9))
  29. * //=> 2
  30. */
  31. export default function getWeekOfMonth(date, dirtyOptions) {
  32. requiredArgs(1, arguments);
  33. var options = dirtyOptions || {};
  34. var locale = options.locale;
  35. var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
  36. var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
  37. var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
  38. if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
  39. throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
  40. }
  41. var currentDayOfMonth = getDate(date);
  42. if (isNaN(currentDayOfMonth)) {
  43. return currentDayOfMonth;
  44. }
  45. var startWeekDay = getDay(startOfMonth(date));
  46. var lastDayOfFirstWeek = 0;
  47. if (startWeekDay >= weekStartsOn) {
  48. lastDayOfFirstWeek = weekStartsOn + 7 - startWeekDay;
  49. } else {
  50. lastDayOfFirstWeek = weekStartsOn - startWeekDay;
  51. }
  52. var weekNumber = 1;
  53. if (currentDayOfMonth > lastDayOfFirstWeek) {
  54. var remainingDaysAfterFirstWeek = currentDayOfMonth - lastDayOfFirstWeek;
  55. weekNumber = weekNumber + Math.ceil(remainingDaysAfterFirstWeek / 7);
  56. }
  57. return weekNumber;
  58. }