index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import addDays from "../addDays/index.js";
  2. import toDate from "../toDate/index.js";
  3. import toInteger from "../_lib/toInteger/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. /**
  6. * @name setDay
  7. * @category Weekday Helpers
  8. * @summary Set the day of the week to the given date.
  9. *
  10. * @description
  11. * Set the day of the week to the given date.
  12. *
  13. * ### v2.0.0 breaking changes:
  14. *
  15. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  16. *
  17. * @param {Date|Number} date - the date to be changed
  18. * @param {Number} day - the day of the week of the new date
  19. * @param {Object} [options] - an object with options.
  20. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  21. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  22. * @returns {Date} the new date with the day of the week set
  23. * @throws {TypeError} 2 arguments required
  24. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  25. *
  26. * @example
  27. * // Set week day to Sunday, with the default weekStartsOn of Sunday:
  28. * var 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. * var result = setDay(new Date(2014, 8, 1), 0, { weekStartsOn: 1 })
  34. * //=> Sun Sep 07 2014 00:00:00
  35. */
  36. export default function setDay(dirtyDate, dirtyDay, dirtyOptions) {
  37. requiredArgs(2, arguments);
  38. var options = dirtyOptions || {};
  39. var locale = options.locale;
  40. var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
  41. var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
  42. var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
  43. if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
  44. throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
  45. }
  46. var date = toDate(dirtyDate, options);
  47. var day = toInteger(dirtyDay);
  48. var currentDay = date.getDay();
  49. var remainder = day % 7;
  50. var dayIndex = (remainder + 7) % 7;
  51. var delta = 7 - weekStartsOn;
  52. var diff = day < 0 || day > 6 ? day - (currentDay + delta) % 7 : (dayIndex + delta) % 7 - (currentDay + delta) % 7;
  53. return addDays(date, diff, options);
  54. }