startOfWeekYear.mjs 2.3 KB

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