setWeek.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. exports.setWeek = setWeek;
  3. var _index = require("./getWeek.js");
  4. var _index2 = require("./toDate.js");
  5. /**
  6. * The {@link setWeek} function options.
  7. */
  8. /**
  9. * @name setWeek
  10. * @category Week Helpers
  11. * @summary Set the local week to the given date.
  12. *
  13. * @description
  14. * Set the local week to the given date, saving the weekday number.
  15. * The exact calculation depends on the values of
  16. * `options.weekStartsOn` (which is the index of the first day of the week)
  17. * and `options.firstWeekContainsDate` (which is the day of January, which is always in
  18. * the first week of the week-numbering year)
  19. *
  20. * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
  21. *
  22. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  23. *
  24. * @param date - The date to be changed
  25. * @param week - The week of the new date
  26. * @param options - An object with options
  27. *
  28. * @returns The new date with the local week set
  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. function setWeek(date, week, options) {
  46. const _date = (0, _index2.toDate)(date);
  47. const diff = (0, _index.getWeek)(_date, options) - week;
  48. _date.setDate(_date.getDate() - diff * 7);
  49. return _date;
  50. }