getWeek.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { millisecondsInWeek } from "./constants.js";
  2. import { startOfWeek } from "./startOfWeek.js";
  3. import { startOfWeekYear } from "./startOfWeekYear.js";
  4. import { toDate } from "./toDate.js";
  5. /**
  6. * The {@link getWeek} function options.
  7. */
  8. /**
  9. * @name getWeek
  10. * @category Week Helpers
  11. * @summary Get the local week index of the given date.
  12. *
  13. * @description
  14. * Get the local week index of the given date.
  15. * The exact calculation depends on the values of
  16. * `options.weekStartsOn` (which is the index of the first day of the week)
  17. * and `options.firstWeekContainsDate` (which is the day of January, which is always in
  18. * the first week of the week-numbering year)
  19. *
  20. * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
  21. *
  22. * @param date - The given date
  23. * @param options - An object with options
  24. *
  25. * @returns The week
  26. *
  27. * @example
  28. * // Which week of the local week numbering year is 2 January 2005 with default options?
  29. * const result = getWeek(new Date(2005, 0, 2))
  30. * //=> 2
  31. *
  32. * @example
  33. * // Which week of the local week numbering year is 2 January 2005,
  34. * // if Monday is the first day of the week,
  35. * // and the first week of the year always contains 4 January?
  36. * const result = getWeek(new Date(2005, 0, 2), {
  37. * weekStartsOn: 1,
  38. * firstWeekContainsDate: 4
  39. * })
  40. * //=> 53
  41. */
  42. export function getWeek(date, options) {
  43. const _date = toDate(date, options?.in);
  44. const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options);
  45. // Round the number of weeks to the nearest integer because the number of
  46. // milliseconds in a week is not constant (e.g. it's different in the week of
  47. // the daylight saving time clock shift).
  48. return Math.round(diff / millisecondsInWeek) + 1;
  49. }
  50. // Fallback for modularized imports:
  51. export default getWeek;