endOfWeek.cjs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. exports.endOfWeek = endOfWeek;
  3. var _index = require("./_lib/defaultOptions.cjs");
  4. var _index2 = require("./toDate.cjs");
  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. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  19. *
  20. * @param date - The original date
  21. * @param options - An object with options
  22. *
  23. * @returns The end of a week
  24. *
  25. * @example
  26. * // The end of a week for 2 September 2014 11:55:00:
  27. * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0))
  28. * //=> Sat Sep 06 2014 23:59:59.999
  29. *
  30. * @example
  31. * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00:
  32. * const result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
  33. * //=> Sun Sep 07 2014 23:59:59.999
  34. */
  35. function endOfWeek(date, options) {
  36. const defaultOptions = (0, _index.getDefaultOptions)();
  37. const weekStartsOn =
  38. options?.weekStartsOn ??
  39. options?.locale?.options?.weekStartsOn ??
  40. defaultOptions.weekStartsOn ??
  41. defaultOptions.locale?.options?.weekStartsOn ??
  42. 0;
  43. const _date = (0, _index2.toDate)(date, options?.in);
  44. const day = _date.getDay();
  45. const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
  46. _date.setDate(_date.getDate() + diff);
  47. _date.setHours(23, 59, 59, 999);
  48. return _date;
  49. }