setISOWeek.mjs 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { getISOWeek } from "./getISOWeek.mjs";
  2. import { toDate } from "./toDate.mjs";
  3. /**
  4. * @name setISOWeek
  5. * @category ISO Week Helpers
  6. * @summary Set the ISO week to the given date.
  7. *
  8. * @description
  9. * Set the ISO week to the given date, saving the weekday number.
  10. *
  11. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  12. *
  13. * @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).
  14. *
  15. * @param date - The date to be changed
  16. * @param week - The ISO week of the new date
  17. *
  18. * @returns The new date with the ISO week set
  19. *
  20. * @example
  21. * // Set the 53rd ISO week to 7 August 2004:
  22. * const result = setISOWeek(new Date(2004, 7, 7), 53)
  23. * //=> Sat Jan 01 2005 00:00:00
  24. */
  25. export function setISOWeek(date, week) {
  26. const _date = toDate(date);
  27. const diff = getISOWeek(_date) - week;
  28. _date.setDate(_date.getDate() - diff * 7);
  29. return _date;
  30. }
  31. // Fallback for modularized imports:
  32. export default setISOWeek;