getISOWeek.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { millisecondsInWeek } from "./constants.js";
  2. import { startOfISOWeek } from "./startOfISOWeek.js";
  3. import { startOfISOWeekYear } from "./startOfISOWeekYear.js";
  4. import { toDate } from "./toDate.js";
  5. /**
  6. * The {@link getISOWeek} function options.
  7. */
  8. /**
  9. * @name getISOWeek
  10. * @category ISO Week Helpers
  11. * @summary Get the ISO week of the given date.
  12. *
  13. * @description
  14. * Get the ISO week of the given date.
  15. *
  16. * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date
  17. *
  18. * @param date - The given date
  19. * @param options - The options
  20. *
  21. * @returns The ISO week
  22. *
  23. * @example
  24. * // Which week of the ISO-week numbering year is 2 January 2005?
  25. * const result = getISOWeek(new Date(2005, 0, 2))
  26. * //=> 53
  27. */
  28. export function getISOWeek(date, options) {
  29. const _date = toDate(date, options?.in);
  30. const diff = +startOfISOWeek(_date) - +startOfISOWeekYear(_date);
  31. // Round the number of weeks to the nearest integer because the number of
  32. // milliseconds in a week is not constant (e.g. it's different in the week of
  33. // the daylight saving time clock shift).
  34. return Math.round(diff / millisecondsInWeek) + 1;
  35. }
  36. // Fallback for modularized imports:
  37. export default getISOWeek;