index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var parse = require('../parse/index.js')
  2. var addDays = require('../add_days/index.js')
  3. /**
  4. * @category Weekday Helpers
  5. * @summary Set the day of the week to the given date.
  6. *
  7. * @description
  8. * Set the day of the week to the given date.
  9. *
  10. * @param {Date|String|Number} date - the date to be changed
  11. * @param {Number} day - the day of the week of the new date
  12. * @param {Object} [options] - the object with options
  13. * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  14. * @returns {Date} the new date with the day of the week setted
  15. *
  16. * @example
  17. * // Set Sunday to 1 September 2014:
  18. * var result = setDay(new Date(2014, 8, 1), 0)
  19. * //=> Sun Aug 31 2014 00:00:00
  20. *
  21. * @example
  22. * // If week starts with Monday, set Sunday to 1 September 2014:
  23. * var result = setDay(new Date(2014, 8, 1), 0, {weekStartsOn: 1})
  24. * //=> Sun Sep 07 2014 00:00:00
  25. */
  26. function setDay (dirtyDate, dirtyDay, dirtyOptions) {
  27. var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0
  28. var date = parse(dirtyDate)
  29. var day = Number(dirtyDay)
  30. var currentDay = date.getDay()
  31. var remainder = day % 7
  32. var dayIndex = (remainder + 7) % 7
  33. var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay
  34. return addDays(date, diff)
  35. }
  36. module.exports = setDay