endOfWeek.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. exports.endOfWeek = endOfWeek;
  3. var _index = require("./toDate.js");
  4. var _index2 = require("./_lib/defaultOptions.js");
  5. /**
  6. * The {@link endOfWeek} function options.
  7. */
  8. /**
  9. * @name endOfWeek
  10. * @category Week Helpers
  11. * @summary Return the end of a week for the given date.
  12. *
  13. * @description
  14. * Return the end of a week for the given date.
  15. * The result will be in the local timezone.
  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 original date
  20. * @param options - An object with options
  21. *
  22. * @returns The end of a week
  23. *
  24. * @example
  25. * // The end of a week for 2 September 2014 11:55:00:
  26. * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))
  27. * //=> Sat Sep 06 2014 23:59:59.999
  28. *
  29. * @example
  30. * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:
  31. * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
  32. * //=> Sun Sep 07 2014 23:59:59.999
  33. */
  34. function endOfWeek(date, options) {
  35. const defaultOptions = (0, _index2.getDefaultOptions)();
  36. const weekStartsOn =
  37. options?.weekStartsOn ??
  38. options?.locale?.options?.weekStartsOn ??
  39. defaultOptions.weekStartsOn ??
  40. defaultOptions.locale?.options?.weekStartsOn ??
  41. 0;
  42. const _date = (0, _index.toDate)(date);
  43. const day = _date.getDay();
  44. const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
  45. _date.setDate(_date.getDate() + diff);
  46. _date.setHours(23, 59, 59, 999);
  47. return _date;
  48. }