endOfWeek.mjs 1.6 KB

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