setISOWeekYear.js 1.5 KB

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