getISOWeeksInYear.mjs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { addWeeks } from "./addWeeks.mjs";
  2. import { millisecondsInWeek } from "./constants.mjs";
  3. import { startOfISOWeekYear } from "./startOfISOWeekYear.mjs";
  4. /**
  5. * @name getISOWeeksInYear
  6. * @category ISO Week-Numbering Year Helpers
  7. * @summary Get the number of weeks in an ISO week-numbering year of the given date.
  8. *
  9. * @description
  10. * Get the number of weeks in an ISO week-numbering year of the given date.
  11. *
  12. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  13. *
  14. * @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).
  15. *
  16. * @param date - The given date
  17. *
  18. * @returns The number of ISO weeks in a year
  19. *
  20. * @example
  21. * // How many weeks are in ISO week-numbering year 2015?
  22. * const result = getISOWeeksInYear(new Date(2015, 1, 11))
  23. * //=> 53
  24. */
  25. export function getISOWeeksInYear(date) {
  26. const thisYear = startOfISOWeekYear(date);
  27. const nextYear = startOfISOWeekYear(addWeeks(thisYear, 60));
  28. const diff = +nextYear - +thisYear;
  29. // Round the number of weeks to the nearest integer because the number of
  30. // milliseconds in a week is not constant (e.g. it's different in the week of
  31. // the daylight saving time clock shift).
  32. return Math.round(diff / millisecondsInWeek);
  33. }
  34. // Fallback for modularized imports:
  35. export default getISOWeeksInYear;