getISOWeekYear.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { constructFrom } from "./constructFrom.js";
  2. import { startOfISOWeek } from "./startOfISOWeek.js";
  3. import { toDate } from "./toDate.js";
  4. /**
  5. * The {@link getISOWeekYear} function options.
  6. */
  7. /**
  8. * @name getISOWeekYear
  9. * @category ISO Week-Numbering Year Helpers
  10. * @summary Get the ISO week-numbering year of the given date.
  11. *
  12. * @description
  13. * Get the ISO week-numbering year of the given date,
  14. * which always starts 3 days before the year's first Thursday.
  15. *
  16. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  17. *
  18. * @param date - The given date
  19. *
  20. * @returns The ISO week-numbering year
  21. *
  22. * @example
  23. * // Which ISO-week numbering year is 2 January 2005?
  24. * const result = getISOWeekYear(new Date(2005, 0, 2))
  25. * //=> 2004
  26. */
  27. export function getISOWeekYear(date, options) {
  28. const _date = toDate(date, options?.in);
  29. const year = _date.getFullYear();
  30. const fourthOfJanuaryOfNextYear = constructFrom(_date, 0);
  31. fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4);
  32. fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0);
  33. const startOfNextYear = startOfISOWeek(fourthOfJanuaryOfNextYear);
  34. const fourthOfJanuaryOfThisYear = constructFrom(_date, 0);
  35. fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4);
  36. fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0);
  37. const startOfThisYear = startOfISOWeek(fourthOfJanuaryOfThisYear);
  38. if (_date.getTime() >= startOfNextYear.getTime()) {
  39. return year + 1;
  40. } else if (_date.getTime() >= startOfThisYear.getTime()) {
  41. return year;
  42. } else {
  43. return year - 1;
  44. }
  45. }
  46. // Fallback for modularized imports:
  47. export default getISOWeekYear;