getWeek.js 1.9 KB

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