setDay.cjs 1.9 KB

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