startOfWeek.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. exports.startOfWeek = startOfWeek;
  3. var _index = require("./toDate.js");
  4. var _index2 = require("./_lib/defaultOptions.js");
  5. /**
  6. * The {@link startOfWeek} function options.
  7. */
  8. /**
  9. * @name startOfWeek
  10. * @category Week Helpers
  11. * @summary Return the start of a week for the given date.
  12. *
  13. * @description
  14. * Return the start 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 start of a week
  23. *
  24. * @example
  25. * // The start of a week for 2 September 2014 11:55:00:
  26. * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0))
  27. * //=> Sun Aug 31 2014 00:00:00
  28. *
  29. * @example
  30. * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00:
  31. * const result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), { weekStartsOn: 1 })
  32. * //=> Mon Sep 01 2014 00:00:00
  33. */
  34. function startOfWeek(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) + day - weekStartsOn;
  45. _date.setDate(_date.getDate() - diff);
  46. _date.setHours(0, 0, 0, 0);
  47. return _date;
  48. }