index.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import getWeek from "../getWeek/index.js";
  2. import toDate from "../toDate/index.js";
  3. import requiredArgs from "../_lib/requiredArgs/index.js";
  4. import toInteger from "../_lib/toInteger/index.js";
  5. /**
  6. * @name setWeek
  7. * @category Week Helpers
  8. * @summary Set the local week to the given date.
  9. *
  10. * @description
  11. * Set the local week to the given date, saving the weekday number.
  12. * The exact calculation depends on the values of
  13. * `options.weekStartsOn` (which is the index of the first day of the week)
  14. * and `options.firstWeekContainsDate` (which is the day of January, which is always in
  15. * the first week of the week-numbering year)
  16. *
  17. * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering
  18. *
  19. * @param {Date|Number} date - the date to be changed
  20. * @param {Number} week - the week of the new date
  21. * @param {Object} [options] - an object with options.
  22. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  23. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  24. * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year
  25. * @returns {Date} the new date with the local week set
  26. * @throws {TypeError} 2 arguments required
  27. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  28. * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
  29. *
  30. * @example
  31. * // Set the 1st week to 2 January 2005 with default options:
  32. * const result = setWeek(new Date(2005, 0, 2), 1)
  33. * //=> Sun Dec 26 2004 00:00:00
  34. *
  35. * @example
  36. * // Set the 1st week to 2 January 2005,
  37. * // if Monday is the first day of the week,
  38. * // and the first week of the year always contains 4 January:
  39. * const result = setWeek(new Date(2005, 0, 2), 1, {
  40. * weekStartsOn: 1,
  41. * firstWeekContainsDate: 4
  42. * })
  43. * //=> Sun Jan 4 2004 00:00:00
  44. */
  45. export default function setWeek(dirtyDate, dirtyWeek, options) {
  46. requiredArgs(2, arguments);
  47. var date = toDate(dirtyDate);
  48. var week = toInteger(dirtyWeek);
  49. var diff = getWeek(date, options) - week;
  50. date.setDate(date.getDate() - diff * 7);
  51. return date;
  52. }