getWeek.cjs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use strict";
  2. exports.getWeek = getWeek;
  3. var _index = require("./constants.cjs");
  4. var _index2 = require("./startOfWeek.cjs");
  5. var _index3 = require("./startOfWeekYear.cjs");
  6. var _index4 = require("./toDate.cjs");
  7. /**
  8. * The {@link getWeek} function options.
  9. */
  10. /**
  11. * @name getWeek
  12. * @category Week Helpers
  13. * @summary Get the local week index of the given date.
  14. *
  15. * @description
  16. * Get the local week index of the given date.
  17. * The exact calculation depends on the values of
  18. * `options.weekStartsOn` (which is the index of the first day of the week)
  19. * and `options.firstWeekContainsDate` (which is the day of January, which is always in
  20. * the first week of the week-numbering year)
  21. *
  22. * Week numbering: https://en.wikipedia.org/wiki/Week#The_ISO_week_date_system
  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. function getWeek(date, options) {
  45. const _date = (0, _index4.toDate)(date, options?.in);
  46. const diff =
  47. +(0, _index2.startOfWeek)(_date, options) -
  48. +(0, _index3.startOfWeekYear)(_date, options);
  49. // Round the number of weeks to the nearest integer because the number of
  50. // milliseconds in a week is not constant (e.g. it's different in the week of
  51. // the daylight saving time clock shift).
  52. return Math.round(diff / _index.millisecondsInWeek) + 1;
  53. }