setDay.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { getDefaultOptions } from "./_lib/defaultOptions.js";
  2. import { addDays } from "./addDays.js";
  3. import { toDate } from "./toDate.js";
  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. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  17. *
  18. * @param date - The date to be changed
  19. * @param day - The day of the week of the new date
  20. * @param options - An object with options.
  21. *
  22. * @returns The new date with the day of the week set
  23. *
  24. * @example
  25. * // Set week day to Sunday, with the default weekStartsOn of Sunday:
  26. * const result = setDay(new Date(2014, 8, 1), 0)
  27. * //=> Sun Aug 31 2014 00:00:00
  28. *
  29. * @example
  30. * // Set week day to Sunday, with a weekStartsOn of Monday:
  31. * const result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 })
  32. * //=> Sun Sep 07 2014 00:00:00
  33. */
  34. export function setDay(date, day, options) {
  35. const defaultOptions = getDefaultOptions();
  36. const weekStartsOn =
  37. options?.weekStartsOn ??
  38. options?.locale?.options?.weekStartsOn ??
  39. defaultOptions.weekStartsOn ??
  40. defaultOptions.locale?.options?.weekStartsOn ??
  41. 0;
  42. const date_ = toDate(date, options?.in);
  43. const currentDay = date_.getDay();
  44. const remainder = day % 7;
  45. const dayIndex = (remainder + 7) % 7;
  46. const delta = 7 - weekStartsOn;
  47. const diff =
  48. day < 0 || day > 6
  49. ? day - ((currentDay + delta) % 7)
  50. : ((dayIndex + delta) % 7) - ((currentDay + delta) % 7);
  51. return addDays(date_, diff, options);
  52. }
  53. // Fallback for modularized imports:
  54. export default setDay;