startOfWeekYear.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. exports.startOfWeekYear = startOfWeekYear;
  3. var _index = require("./constructFrom.js");
  4. var _index2 = require("./getWeekYear.js");
  5. var _index3 = require("./startOfWeek.js");
  6. var _index4 = require("./_lib/defaultOptions.js");
  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. *
  26. * @param date - The original date
  27. * @param options - An object with options
  28. *
  29. * @returns The start of a week-numbering year
  30. *
  31. * @example
  32. * // The start of an a week-numbering year for 2 July 2005 with default settings:
  33. * const result = startOfWeekYear(new Date(2005, 6, 2))
  34. * //=> Sun Dec 26 2004 00:00:00
  35. *
  36. * @example
  37. * // The start of a week-numbering year for 2 July 2005
  38. * // if Monday is the first day of week
  39. * // and 4 January is always in the first week of the year:
  40. * const result = startOfWeekYear(new Date(2005, 6, 2), {
  41. * weekStartsOn: 1,
  42. * firstWeekContainsDate: 4
  43. * })
  44. * //=> Mon Jan 03 2005 00:00:00
  45. */
  46. function startOfWeekYear(date, options) {
  47. const defaultOptions = (0, _index4.getDefaultOptions)();
  48. const firstWeekContainsDate =
  49. options?.firstWeekContainsDate ??
  50. options?.locale?.options?.firstWeekContainsDate ??
  51. defaultOptions.firstWeekContainsDate ??
  52. defaultOptions.locale?.options?.firstWeekContainsDate ??
  53. 1;
  54. const year = (0, _index2.getWeekYear)(date, options);
  55. const firstWeek = (0, _index.constructFrom)(date, 0);
  56. firstWeek.setFullYear(year, 0, firstWeekContainsDate);
  57. firstWeek.setHours(0, 0, 0, 0);
  58. const _date = (0, _index3.startOfWeek)(firstWeek, options);
  59. return _date;
  60. }