lastDayOfWeek.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { getDefaultOptions } from "./_lib/defaultOptions.js";
  2. import { toDate } from "./toDate.js";
  3. /**
  4. * The {@link lastDayOfWeek} function options.
  5. */
  6. /**
  7. * @name lastDayOfWeek
  8. * @category Week Helpers
  9. * @summary Return the last day of a week for the given date.
  10. *
  11. * @description
  12. * Return the last day of a week for the given date.
  13. * The result will be in the local timezone unless a context is specified.
  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. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  17. *
  18. * @param date - The original date
  19. * @param options - An object with options
  20. *
  21. * @returns The last day of a week
  22. */
  23. export function lastDayOfWeek(date, options) {
  24. const defaultOptions = getDefaultOptions();
  25. const weekStartsOn =
  26. options?.weekStartsOn ??
  27. options?.locale?.options?.weekStartsOn ??
  28. defaultOptions.weekStartsOn ??
  29. defaultOptions.locale?.options?.weekStartsOn ??
  30. 0;
  31. const _date = toDate(date, options?.in);
  32. const day = _date.getDay();
  33. const diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn);
  34. _date.setHours(0, 0, 0, 0);
  35. _date.setDate(_date.getDate() + diff);
  36. return _date;
  37. }
  38. // Fallback for modularized imports:
  39. export default lastDayOfWeek;