index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. * @param {Date|Number} date - the given date
  16. * @returns {Number} the ISO week-numbering year
  17. * @throws {TypeError} 1 argument required
  18. *
  19. * @example
  20. * // Which ISO-week numbering year is 2 January 2005?
  21. * const result = getISOWeekYear(new Date(2005, 0, 2))
  22. * //=> 2004
  23. */
  24. export default function getISOWeekYear(dirtyDate) {
  25. requiredArgs(1, arguments);
  26. var date = toDate(dirtyDate);
  27. var year = date.getFullYear();
  28. var fourthOfJanuaryOfNextYear = new Date(0);
  29. fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
  30. fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
  31. var startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);
  32. var fourthOfJanuaryOfThisYear = new Date(0);
  33. fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
  34. fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
  35. var startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);
  36. if (date.getTime() >= startOfNextYear.getTime()) {
  37. return year + 1;
  38. } else if (date.getTime() >= startOfThisYear.getTime()) {
  39. return year;
  40. } else {
  41. return year - 1;
  42. }
  43. }