index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import startOfWeek from "../startOfWeek/index.js";
  2. import startOfWeekYear from "../startOfWeekYear/index.js";
  3. import toDate from "../toDate/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. var MILLISECONDS_IN_WEEK = 604800000;
  6. /**
  7. * @name getWeek
  8. * @category Week Helpers
  9. * @summary Get the local week index of the given date.
  10. *
  11. * @description
  12. * Get the local week index of the given date.
  13. * The exact calculation depends on the values of
  14. * `options.weekStartsOn` (which is the index of the first day of the week)
  15. * and `options.firstWeekContainsDate` (which is the day of January, which is always in
  16. * the first week of the week-numbering year)
  17. *
  18. * Week numbering: https://en.wikipedia.org/wiki/Week#Week_numbering
  19. *
  20. * ### v2.0.0 breaking changes:
  21. *
  22. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  23. *
  24. * @param {Date|Number} date - the given date
  25. * @param {Object} [options] - an object with options.
  26. * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
  27. * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
  28. * @param {1|2|3|4|5|6|7} [options.firstWeekContainsDate=1] - the day of January, which is always in the first week of the year
  29. * @returns {Number} the week
  30. * @throws {TypeError} 1 argument required
  31. * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
  32. * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
  33. *
  34. * @example
  35. * // Which week of the local week numbering year is 2 January 2005 with default options?
  36. * const result = getISOWeek(new Date(2005, 0, 2))
  37. * //=> 2
  38. *
  39. * // Which week of the local week numbering year is 2 January 2005,
  40. * // if Monday is the first day of the week,
  41. * // and the first week of the year always contains 4 January?
  42. * const result = getISOWeek(new Date(2005, 0, 2), {
  43. * weekStartsOn: 1,
  44. * firstWeekContainsDate: 4
  45. * })
  46. * //=> 53
  47. */
  48. export default function getWeek(dirtyDate, options) {
  49. requiredArgs(1, arguments);
  50. var date = toDate(dirtyDate);
  51. var diff = startOfWeek(date, options).getTime() - startOfWeekYear(date, options).getTime(); // Round the number of days to the nearest integer
  52. // because the number of milliseconds in a week is not constant
  53. // (e.g. it's different in the week of the daylight saving time clock shift)
  54. return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
  55. }