index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import toDate from "../toDate/index.js";
  2. import toInteger from "../_lib/toInteger/index.js";
  3. import requiredArgs from "../_lib/requiredArgs/index.js";
  4. /**
  5. * @name lastDayOfWeek
  6. * @category Week Helpers
  7. * @summary Return the last day of a week for the given date.
  8. *
  9. * @description
  10. * Return the last day of a week for the given date.
  11. * The result will be in the local timezone.
  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 original date
  18. * @param {Object} [options] - an object with options.
  19. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  20. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  21. * @returns {Date} the last day of a week
  22. * @throws {TypeError} 1 argument required
  23. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  24. *
  25. * @example
  26. * // The last day of a week for 2 September 2014 11:55:00:
  27. * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0))
  28. * //=> Sat Sep 06 2014 00:00:00
  29. *
  30. * @example
  31. * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00:
  32. * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
  33. * //=> Sun Sep 07 2014 00:00:00
  34. */
  35. export default function lastDayOfWeek(dirtyDate, dirtyOptions) {
  36. requiredArgs(1, arguments);
  37. var options = dirtyOptions || {};
  38. var locale = options.locale;
  39. var localeWeekStartsOn = locale && locale.options && locale.options.weekStartsOn;
  40. var defaultWeekStartsOn = localeWeekStartsOn == null ? 0 : toInteger(localeWeekStartsOn);
  41. var weekStartsOn = options.weekStartsOn == null ? defaultWeekStartsOn : toInteger(options.weekStartsOn); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
  42. if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
  43. throw new RangeError('weekStartsOn must be between 0 and 6');
  44. }
  45. var date = toDate(dirtyDate);
  46. var day = date.getDay();
  47. var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
  48. date.setHours(0, 0, 0, 0);
  49. date.setDate(date.getDate() + diff);
  50. return date;
  51. }