index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import toInteger from "../_lib/toInteger/index.js";
  2. import toDate from "../toDate/index.js";
  3. import startOfISOWeekYear from "../startOfISOWeekYear/index.js";
  4. import differenceInCalendarDays from "../differenceInCalendarDays/index.js";
  5. import requiredArgs from "../_lib/requiredArgs/index.js";
  6. /**
  7. * @name setISOWeekYear
  8. * @category ISO Week-Numbering Year Helpers
  9. * @summary Set the ISO week-numbering year to the given date.
  10. *
  11. * @description
  12. * Set the ISO week-numbering year to the given date,
  13. * saving the week number and the weekday number.
  14. *
  15. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  16. *
  17. * ### v2.0.0 breaking changes:
  18. *
  19. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  20. *
  21. * - The function was renamed from `setISOYear` to `setISOWeekYear`.
  22. * "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
  23. * This change makes the name consistent with
  24. * locale-dependent week-numbering year helpers, e.g., `setWeekYear`.
  25. *
  26. * @param {Date|Number} date - the date to be changed
  27. * @param {Number} isoWeekYear - the ISO week-numbering year of the new date
  28. * @returns {Date} the new date with the ISO week-numbering year set
  29. * @throws {TypeError} 2 arguments required
  30. *
  31. * @example
  32. * // Set ISO week-numbering year 2007 to 29 December 2008:
  33. * const result = setISOWeekYear(new Date(2008, 11, 29), 2007)
  34. * //=> Mon Jan 01 2007 00:00:00
  35. */
  36. export default function setISOWeekYear(dirtyDate, dirtyISOWeekYear) {
  37. requiredArgs(2, arguments);
  38. var date = toDate(dirtyDate);
  39. var isoWeekYear = toInteger(dirtyISOWeekYear);
  40. var diff = differenceInCalendarDays(date, startOfISOWeekYear(date));
  41. var fourthOfJanuary = new Date(0);
  42. fourthOfJanuary.setFullYear(isoWeekYear, 0, 4);
  43. fourthOfJanuary.setHours(0, 0, 0, 0);
  44. date = startOfISOWeekYear(fourthOfJanuary);
  45. date.setDate(date.getDate() + diff);
  46. return date;
  47. }