setWeek.mjs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { getWeek } from "./getWeek.mjs";
  2. import { toDate } from "./toDate.mjs";
  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. *
  22. * @param date - The date to be changed
  23. * @param week - The week of the new date
  24. * @param options - An object with options
  25. *
  26. * @returns The new date with the local week set
  27. *
  28. * @example
  29. * // Set the 1st week to 2 January 2005 with default options:
  30. * const result = setWeek(new Date(2005, 0, 2), 1)
  31. * //=> Sun Dec 26 2004 00:00:00
  32. *
  33. * @example
  34. * // Set the 1st week to 2 January 2005,
  35. * // if Monday is the first day of the week,
  36. * // and the first week of the year always contains 4 January:
  37. * const result = setWeek(new Date(2005, 0, 2), 1, {
  38. * weekStartsOn: 1,
  39. * firstWeekContainsDate: 4
  40. * })
  41. * //=> Sun Jan 4 2004 00:00:00
  42. */
  43. export function setWeek(date, week, options) {
  44. const _date = toDate(date);
  45. const diff = getWeek(_date, options) - week;
  46. _date.setDate(_date.getDate() - diff * 7);
  47. return _date;
  48. }
  49. // Fallback for modularized imports:
  50. export default setWeek;