setISOWeekYear.mjs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { constructFrom } from "./constructFrom.mjs";
  2. import { differenceInCalendarDays } from "./differenceInCalendarDays.mjs";
  3. import { startOfISOWeekYear } from "./startOfISOWeekYear.mjs";
  4. import { toDate } from "./toDate.mjs";
  5. /**
  6. * @name setISOWeekYear
  7. * @category ISO Week-Numbering Year Helpers
  8. * @summary Set the ISO week-numbering year to the given date.
  9. *
  10. * @description
  11. * Set the ISO week-numbering year to the given date,
  12. * saving the week number and the weekday number.
  13. *
  14. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  15. *
  16. * @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).
  17. *
  18. * @param date - The date to be changed
  19. * @param weekYear - The ISO week-numbering year of the new date
  20. *
  21. * @returns The new date with the ISO week-numbering year set
  22. *
  23. * @example
  24. * // Set ISO week-numbering year 2007 to 29 December 2008:
  25. * const result = setISOWeekYear(new Date(2008, 11, 29), 2007)
  26. * //=> Mon Jan 01 2007 00:00:00
  27. */
  28. export function setISOWeekYear(date, weekYear) {
  29. let _date = toDate(date);
  30. const diff = differenceInCalendarDays(_date, startOfISOWeekYear(_date));
  31. const fourthOfJanuary = constructFrom(date, 0);
  32. fourthOfJanuary.setFullYear(weekYear, 0, 4);
  33. fourthOfJanuary.setHours(0, 0, 0, 0);
  34. _date = startOfISOWeekYear(fourthOfJanuary);
  35. _date.setDate(_date.getDate() + diff);
  36. return _date;
  37. }
  38. // Fallback for modularized imports:
  39. export default setISOWeekYear;