index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import toDate from "../toDate/index.js";
  2. import startOfISOWeek from "../startOfISOWeek/index.js";
  3. import requiredArgs from "../_lib/requiredArgs/index.js";
  4. /**
  5. * @name getISOWeekYear
  6. * @category ISO Week-Numbering Year Helpers
  7. * @summary Get the ISO week-numbering year of the given date.
  8. *
  9. * @description
  10. * Get the ISO week-numbering year of the given date,
  11. * which always starts 3 days before the year's first Thursday.
  12. *
  13. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  14. *
  15. * ### v2.0.0 breaking changes:
  16. *
  17. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  18. *
  19. * - The function was renamed from `getISOYear` to `getISOWeekYear`.
  20. * "ISO week year" is short for [ISO week-numbering year](https://en.wikipedia.org/wiki/ISO_week_date).
  21. * This change makes the name consistent with
  22. * locale-dependent week-numbering year helpers, e.g., `getWeekYear`.
  23. *
  24. * @param {Date|Number} date - the given date
  25. * @returns {Number} the ISO week-numbering year
  26. * @throws {TypeError} 1 argument required
  27. *
  28. * @example
  29. * // Which ISO-week numbering year is 2 January 2005?
  30. * const result = getISOWeekYear(new Date(2005, 0, 2))
  31. * //=> 2004
  32. */
  33. export default function getISOWeekYear(dirtyDate) {
  34. requiredArgs(1, arguments);
  35. var date = toDate(dirtyDate);
  36. var year = date.getFullYear();
  37. var fourthOfJanuaryOfNextYear = new Date(0);
  38. fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
  39. fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
  40. var startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);
  41. var fourthOfJanuaryOfThisYear = new Date(0);
  42. fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
  43. fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
  44. var startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);
  45. if (date.getTime() >= startOfNextYear.getTime()) {
  46. return year + 1;
  47. } else if (date.getTime() >= startOfThisYear.getTime()) {
  48. return year;
  49. } else {
  50. return year - 1;
  51. }
  52. }