setWeek.cjs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. exports.setWeek = setWeek;
  3. var _index = require("./getWeek.cjs");
  4. var _index2 = require("./toDate.cjs");
  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. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  24. *
  25. * @param date - The date to be changed
  26. * @param week - The week of the new date
  27. * @param options - An object with options
  28. *
  29. * @returns The new date with the local week set
  30. *
  31. * @example
  32. * // Set the 1st week to 2 January 2005 with default options:
  33. * const result = setWeek(new Date(2005, 0, 2), 1)
  34. * //=> Sun Dec 26 2004 00:00:00
  35. *
  36. * @example
  37. * // Set the 1st week to 2 January 2005,
  38. * // if Monday is the first day of the week,
  39. * // and the first week of the year always contains 4 January:
  40. * const result = setWeek(new Date(2005, 0, 2), 1, {
  41. * weekStartsOn: 1,
  42. * firstWeekContainsDate: 4
  43. * })
  44. * //=> Sun Jan 4 2004 00:00:00
  45. */
  46. function setWeek(date, week, options) {
  47. const date_ = (0, _index2.toDate)(date, options?.in);
  48. const diff = (0, _index.getWeek)(date_, options) - week;
  49. date_.setDate(date_.getDate() - diff * 7);
  50. return (0, _index2.toDate)(date_, options?.in);
  51. }