Source: setWeek/index.js

  1. import getWeek from '../getWeek/index'
  2. import toDate from '../toDate/index'
  3. import toInteger from '../_lib/toInteger/index'
  4. import requiredArgs from '../_lib/requiredArgs/index'
  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. * ### v2.0.0 breaking changes:
  20. *
  21. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  22. *
  23. * @param {Date|Number} date - the date to be changed
  24. * @param {Number} week - the week of the new date
  25. * @param {Object} [options] - an object with options.
  26. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  27. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  28. * @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
  29. * @returns {Date} the new date with the local week set
  30. * @throws {TypeError} 2 arguments required
  31. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  32. * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
  33. *
  34. * @example
  35. * // Set the 1st week to 2 January 2005 with default options:
  36. * var result = setWeek(new Date(2005, 0, 2), 1)
  37. * //=> Sun Dec 26 2004 00:00:00
  38. *
  39. * @example
  40. * // Set the 1st week to 2 January 2005,
  41. * // if Monday is the first day of the week,
  42. * // and the first week of the year always contains 4 January:
  43. * var result = setWeek(new Date(2005, 0, 2), 1, {
  44. * weekStartsOn: 1,
  45. * firstWeekContainsDate: 4
  46. * })
  47. * //=> Sun Jan 4 2004 00:00:00
  48. */
  49. export default function setWeek(dirtyDate, dirtyWeek, dirtyOptions) {
  50. requiredArgs(2, arguments)
  51. var date = toDate(dirtyDate)
  52. var week = toInteger(dirtyWeek)
  53. var diff = getWeek(date, dirtyOptions) - week
  54. date.setDate(date.getDate() - diff * 7)
  55. return date
  56. }