startOfWeekYear.js 2.3 KB

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