setISOWeekYear.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { constructFrom } from "./constructFrom.js";
  2. import { differenceInCalendarDays } from "./differenceInCalendarDays.js";
  3. import { startOfISOWeekYear } from "./startOfISOWeekYear.js";
  4. import { toDate } from "./toDate.js";
  5. /**
  6. * The {@link setISOWeekYear} function options.
  7. */
  8. /**
  9. * @name setISOWeekYear
  10. * @category ISO Week-Numbering Year Helpers
  11. * @summary Set the ISO week-numbering year to the given date.
  12. *
  13. * @description
  14. * Set the ISO week-numbering year to the given date,
  15. * saving the week number and the weekday number.
  16. *
  17. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  18. *
  19. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows using extensions like [`UTCDate`](https://github.com/date-fns/utc).
  20. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  21. *
  22. * @param date - The date to be changed
  23. * @param weekYear - The ISO week-numbering year of the new date
  24. * @param options - An object with options
  25. *
  26. * @returns The new date with the ISO week-numbering year set
  27. *
  28. * @example
  29. * // Set ISO week-numbering year 2007 to 29 December 2008:
  30. * const result = setISOWeekYear(new Date(2008, 11, 29), 2007)
  31. * //=> Mon Jan 01 2007 00:00:00
  32. */
  33. export function setISOWeekYear(date, weekYear, options) {
  34. let _date = toDate(date, options?.in);
  35. const diff = differenceInCalendarDays(
  36. _date,
  37. startOfISOWeekYear(_date, options),
  38. );
  39. const fourthOfJanuary = constructFrom(options?.in || date, 0);
  40. fourthOfJanuary.setFullYear(weekYear, 0, 4);
  41. fourthOfJanuary.setHours(0, 0, 0, 0);
  42. _date = startOfISOWeekYear(fourthOfJanuary);
  43. _date.setDate(_date.getDate() + diff);
  44. return _date;
  45. }
  46. // Fallback for modularized imports:
  47. export default setISOWeekYear;