setWeek.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { getWeek } from "./getWeek.js";
  2. import { toDate } from "./toDate.js";
  3. /**
  4. * The {@link setWeek} function options.
  5. */
  6. /**
  7. * @name setWeek
  8. * @category Week Helpers
  9. * @summary Set the local week to the given date.
  10. *
  11. * @description
  12. * Set the local week to the given date, saving the weekday number.
  13. * The exact calculation depends on the values of
  14. * `options.weekStartsOn` (which is the index of the first day of the week)
  15. * and `options.firstWeekContainsDate` (which is the day of January, which is always in
  16. * the first week of the week-numbering year)
  17. *
  18. * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
  19. *
  20. * @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).
  21. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  22. *
  23. * @param date - The date to be changed
  24. * @param week - The week of the new date
  25. * @param options - An object with options
  26. *
  27. * @returns The new date with the local week set
  28. *
  29. * @example
  30. * // Set the 1st week to 2 January 2005 with default options:
  31. * const result = setWeek(new Date(2005, 0, 2), 1)
  32. * //=> Sun Dec 26 2004 00:00:00
  33. *
  34. * @example
  35. * // Set the 1st week to 2 January 2005,
  36. * // if Monday is the first day of the week,
  37. * // and the first week of the year always contains 4 January:
  38. * const result = setWeek(new Date(2005, 0, 2), 1, {
  39. * weekStartsOn: 1,
  40. * firstWeekContainsDate: 4
  41. * })
  42. * //=> Sun Jan 4 2004 00:00:00
  43. */
  44. export function setWeek(date, week, options) {
  45. const date_ = toDate(date, options?.in);
  46. const diff = getWeek(date_, options) - week;
  47. date_.setDate(date_.getDate() - diff * 7);
  48. return toDate(date_, options?.in);
  49. }
  50. // Fallback for modularized imports:
  51. export default setWeek;