index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. var parse = require('../parse/index.js')
  2. /**
  3. * @category Week Helpers
  4. * @summary Return the last day of a week for the given date.
  5. *
  6. * @description
  7. * Return the last day of a week for the given date.
  8. * The result will be in the local timezone.
  9. *
  10. * @param {Date|String|Number} date - the original date
  11. * @param {Object} [options] - the object with options
  12. * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  13. * @returns {Date} the last day of a week
  14. *
  15. * @example
  16. * // The last day of a week for 2 September 2014 11:55:00:
  17. * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0))
  18. * //=> Sat Sep 06 2014 00:00:00
  19. *
  20. * @example
  21. * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00:
  22. * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1})
  23. * //=> Sun Sep 07 2014 00:00:00
  24. */
  25. function lastDayOfWeek (dirtyDate, dirtyOptions) {
  26. var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0
  27. var date = parse(dirtyDate)
  28. var day = date.getDay()
  29. var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn)
  30. date.setHours(0, 0, 0, 0)
  31. date.setDate(date.getDate() + diff)
  32. return date
  33. }
  34. module.exports = lastDayOfWeek