startOfWeek.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { getDefaultOptions } from "./_lib/defaultOptions.js";
  2. import { toDate } from "./toDate.js";
  3. /**
  4. * The {@link startOfWeek} function options.
  5. */
  6. /**
  7. * @name startOfWeek
  8. * @category Week Helpers
  9. * @summary Return the start of a week for the given date.
  10. *
  11. * @description
  12. * Return the start 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. * @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 start of a week
  22. *
  23. * @example
  24. * // The start of a week for 2 September 2014 11:55:00:
  25. * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))
  26. * //=> Sun Aug 31 2014 00:00:00
  27. *
  28. * @example
  29. * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:
  30. * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
  31. * //=> Mon Sep 01 2014 00:00:00
  32. */
  33. export function startOfWeek(date, options) {
  34. const defaultOptions = getDefaultOptions();
  35. const weekStartsOn =
  36. options?.weekStartsOn ??
  37. options?.locale?.options?.weekStartsOn ??
  38. defaultOptions.weekStartsOn ??
  39. defaultOptions.locale?.options?.weekStartsOn ??
  40. 0;
  41. const _date = toDate(date, options?.in);
  42. const day = _date.getDay();
  43. const diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
  44. _date.setDate(_date.getDate() - diff);
  45. _date.setHours(0, 0, 0, 0);
  46. return _date;
  47. }
  48. // Fallback for modularized imports:
  49. export default startOfWeek;