setDay.mjs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { addDays } from "./addDays.mjs";
  2. import { toDate } from "./toDate.mjs";
  3. import { getDefaultOptions } from "./_lib/defaultOptions.mjs";
  4. /**
  5. * The {@link setDay} function options.
  6. */
  7. /**
  8. * @name setDay
  9. * @category Weekday Helpers
  10. * @summary Set the day of the week to the given date.
  11. *
  12. * @description
  13. * Set the day of the week to the given date.
  14. *
  15. * @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).
  16. *
  17. * @param date - The date to be changed
  18. * @param day - The day of the week of the new date
  19. * @param options - An object with options.
  20. *
  21. * @returns The new date with the day of the week set
  22. *
  23. * @example
  24. * // Set week day to Sunday, with the default weekStartsOn of Sunday:
  25. * const result = setDay(new Date(2014, 8, 1), 0)
  26. * //=> Sun Aug 31 2014 00:00:00
  27. *
  28. * @example
  29. * // Set week day to Sunday, with a weekStartsOn of Monday:
  30. * const result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 })
  31. * //=> Sun Sep 07 2014 00:00:00
  32. */
  33. export function setDay(date, day, options) {
  34. const defaultOptions = getDefaultOptions();
  35. const weekStartsOn =
  36. options?.weekStartsOn ??
  37. options?.locale?.options?.weekStartsOn ??
  38. defaultOptions.weekStartsOn ??
  39. defaultOptions.locale?.options?.weekStartsOn ??
  40. 0;
  41. const _date = toDate(date);
  42. const currentDay = _date.getDay();
  43. const remainder = day % 7;
  44. const dayIndex = (remainder + 7) % 7;
  45. const delta = 7 - weekStartsOn;
  46. const diff =
  47. day < 0 || day > 6
  48. ? day - ((currentDay + delta) % 7)
  49. : ((dayIndex + delta) % 7) - ((currentDay + delta) % 7);
  50. return addDays(_date, diff);
  51. }
  52. // Fallback for modularized imports:
  53. export default setDay;