getISOWeek.mjs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { millisecondsInWeek } from "./constants.mjs";
  2. import { startOfISOWeek } from "./startOfISOWeek.mjs";
  3. import { startOfISOWeekYear } from "./startOfISOWeekYear.mjs";
  4. import { toDate } from "./toDate.mjs";
  5. /**
  6. * @name getISOWeek
  7. * @category ISO Week Helpers
  8. * @summary Get the ISO week of the given date.
  9. *
  10. * @description
  11. * Get the ISO week of the given date.
  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
  20. *
  21. * @example
  22. * // Which week of the ISO-week numbering year is 2 January 2005?
  23. * const result = getISOWeek(new Date(2005, 0, 2))
  24. * //=> 53
  25. */
  26. export function getISOWeek(date) {
  27. const _date = toDate(date);
  28. const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date);
  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) + 1;
  33. }
  34. // Fallback for modularized imports:
  35. export default getISOWeek;