setDay.js 1.7 KB

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