startOfWeekYear.cjs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. exports.startOfWeekYear = startOfWeekYear;
  3. var _index = require("./_lib/defaultOptions.cjs");
  4. var _index2 = require("./constructFrom.cjs");
  5. var _index3 = require("./getWeekYear.cjs");
  6. var _index4 = require("./startOfWeek.cjs");
  7. /**
  8. * The {@link startOfWeekYear} function options.
  9. */
  10. /**
  11. * @name startOfWeekYear
  12. * @category Week-Numbering Year Helpers
  13. * @summary Return the start of a local week-numbering year for the given date.
  14. *
  15. * @description
  16. * Return the start of a local week-numbering year.
  17. * The exact calculation depends on the values of
  18. * `options.weekStartsOn` (which is the index of the first day of the week)
  19. * and `options.firstWeekContainsDate` (which is the day of January, which is always in
  20. * the first week of the week-numbering year)
  21. *
  22. * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
  23. *
  24. * @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).
  25. * @typeParam ResultDate - The result `Date` type.
  26. *
  27. * @param date - The original date
  28. * @param options - An object with options
  29. *
  30. * @returns The start of a week-numbering year
  31. *
  32. * @example
  33. * // The start of an a week-numbering year for 2 July 2005 with default settings:
  34. * const result = startOfWeekYear(new Date(2005, 6, 2))
  35. * //=> Sun Dec 26 2004 00:00:00
  36. *
  37. * @example
  38. * // The start of a week-numbering year for 2 July 2005
  39. * // if Monday is the first day of week
  40. * // and 4 January is always in the first week of the year:
  41. * const result = startOfWeekYear(new Date(2005, 6, 2), {
  42. * weekStartsOn: 1,
  43. * firstWeekContainsDate: 4
  44. * })
  45. * //=> Mon Jan 03 2005 00:00:00
  46. */
  47. function startOfWeekYear(date, options) {
  48. const defaultOptions = (0, _index.getDefaultOptions)();
  49. const firstWeekContainsDate =
  50. options?.firstWeekContainsDate ??
  51. options?.locale?.options?.firstWeekContainsDate ??
  52. defaultOptions.firstWeekContainsDate ??
  53. defaultOptions.locale?.options?.firstWeekContainsDate ??
  54. 1;
  55. const year = (0, _index3.getWeekYear)(date, options);
  56. const firstWeek = (0, _index2.constructFrom)(options?.in || date, 0);
  57. firstWeek.setFullYear(year, 0, firstWeekContainsDate);
  58. firstWeek.setHours(0, 0, 0, 0);
  59. const _date = (0, _index4.startOfWeek)(firstWeek, options);
  60. return _date;
  61. }