getWeek.mjs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { millisecondsInWeek } from "./constants.mjs";
  2. import { startOfWeek } from "./startOfWeek.mjs";
  3. import { startOfWeekYear } from "./startOfWeekYear.mjs";
  4. import { toDate } from "./toDate.mjs";
  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. * @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).
  23. *
  24. * @param date - The given date
  25. * @param options - An object with options
  26. *
  27. * @returns The week
  28. *
  29. * @example
  30. * // Which week of the local week numbering year is 2 January 2005 with default options?
  31. * const result = getWeek(new Date(2005, 0, 2))
  32. * //=> 2
  33. *
  34. * @example
  35. * // Which week of the local week numbering year is 2 January 2005,
  36. * // if Monday is the first day of the week,
  37. * // and the first week of the year always contains 4 January?
  38. * const result = getWeek(new Date(2005, 0, 2), {
  39. * weekStartsOn: 1,
  40. * firstWeekContainsDate: 4
  41. * })
  42. * //=> 53
  43. */
  44. export function getWeek(date, options) {
  45. const _date = toDate(date);
  46. const diff = +startOfWeek(_date, options) - +startOfWeekYear(_date, options);
  47. // Round the number of weeks to the nearest integer because the number of
  48. // milliseconds in a week is not constant (e.g. it's different in the week of
  49. // the daylight saving time clock shift).
  50. return Math.round(diff / millisecondsInWeek) + 1;
  51. }
  52. // Fallback for modularized imports:
  53. export default getWeek;