setISODay.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { addDays } from "./addDays.js";
  2. import { getISODay } from "./getISODay.js";
  3. import { toDate } from "./toDate.js";
  4. /**
  5. * The {@link setISODay} function options.
  6. */
  7. /**
  8. * @name setISODay
  9. * @category Weekday Helpers
  10. * @summary Set the day of the ISO week to the given date.
  11. *
  12. * @description
  13. * Set the day of the ISO week to the given date.
  14. * ISO week starts with Monday.
  15. * 7 is the index of Sunday, 1 is the index of Monday, etc.
  16. *
  17. * @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).
  18. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  19. *
  20. * @param date - The date to be changed
  21. * @param day - The day of the ISO week of the new date
  22. * @param options - An object with options
  23. *
  24. * @returns The new date with the day of the ISO week set
  25. *
  26. * @example
  27. * // Set Sunday to 1 September 2014:
  28. * const result = setISODay(new Date(2014, 8, 1), 7)
  29. * //=> Sun Sep 07 2014 00:00:00
  30. */
  31. export function setISODay(date, day, options) {
  32. const date_ = toDate(date, options?.in);
  33. const currentDay = getISODay(date_, options);
  34. const diff = day - currentDay;
  35. return addDays(date_, diff, options);
  36. }
  37. // Fallback for modularized imports:
  38. export default setISODay;