getISOWeekYear.mjs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { constructFrom } from "./constructFrom.mjs";
  2. import { startOfISOWeek } from "./startOfISOWeek.mjs";
  3. import { toDate } from "./toDate.mjs";
  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. * @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).
  16. *
  17. * @param date - The given date
  18. *
  19. * @returns The ISO week-numbering year
  20. *
  21. * @example
  22. * // Which ISO-week numbering year is 2 January 2005?
  23. * const result = getISOWeekYear(new Date(2005, 0, 2))
  24. * //=> 2004
  25. */
  26. export function getISOWeekYear(date) {
  27. const _date = toDate(date);
  28. const year = _date.getFullYear();
  29. const fourthOfJanuaryOfNextYear = constructFrom(date, 0);
  30. fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
  31. fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
  32. const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);
  33. const fourthOfJanuaryOfThisYear = constructFrom(date, 0);
  34. fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
  35. fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
  36. const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);
  37. if (_date.getTime() >= startOfNextYear.getTime()) {
  38. return year + 1;
  39. } else if (_date.getTime() >= startOfThisYear.getTime()) {
  40. return year;
  41. } else {
  42. return year - 1;
  43. }
  44. }
  45. // Fallback for modularized imports:
  46. export default getISOWeekYear;