getISOWeekYear.js 1.7 KB

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